I'm making a text based adventure game with java, im a first year computer science student.
I made a room, exit, creature, item and world class and put in the API that was given to me in the class. It was just basic methods and some constructors.
We're suppose to create a textAdventure class were we bring together all the other classes and create the game.
The player and game class was given to me and my professor did all the necessary code in order to make the game run in that class.
My problem is I don't know how to start in my TextAdventure Class, also thats where my main method is.
So I'm confused on how to make a starting room and how to put an exit in that room leading to another room.
Here's some code
public class MyTextAdventure {
private Room room1;
private Room room2;
private Room room3;
private Room room4;
private Room room5;
private Room room6;
private Room room7;
private Room room9;
private Room room10;
public static void main(String [] args){
}
If I wanted to make a player start in room1, can I just do this.
public static void main(String [] args){
public Room startingRoom;
}
I have already declared startingRoom in the room class.
I'm sorry if my skills are bad, I just have no idea what I'm doing and where to start.
Use an array to keep track of your rooms. This allows you to avoid having to keep track of 10 different variable names. It also allows you to do math on the array index. For example, if you wanted to set the current room from 3 to 4, you wouldn't have to check which room was set to current. You could just do currentRoom++
Try something like this.
public class MyTextAdventure {
private Room[] rooms; //array for all rooms
int currentRoom = 0;
boolean over;
//class constructor
public MyTextAdventure() {
rooms = new Room[10]; //Initialize new room array of size 10
over = false; //game is not over yet
for(int i = 0; i < rooms.length; i++) {
//Initialize all rooms
rooms[i] = new Room();
}
}
public void start() {
//do your game loop in here
while(!over) {
}
}
}
public static void main(String [] args){
MyTextAdventure adventure = new MyTextAdventure();
adventure.start();
}
The main function should just start your game. Functions and classes should be designed to accomplish a singular task that is clear. Name classes, functions and variables so that you know exactly what they are doing.
Using the current room as an integer allows you to make use of it as an array index. For example if you want to get the current room you can do this for a function.
public Room getCurrentRoom() {
return rooms[currentRoom];
}
Related
Starting of I want to apologise for my english as I'm not a native speaker. The title might be a bit off since I was not sure how to phrase it but hopefully it will come through once I show my code.
The problem I'm phasing is I want to use the shop class to handle any purchases while storing the money variable on the player class.
Is there any way to access the money integer of the player class without creating an object of the player class in the shop class ?
I was thinking about using a static integer to store the data in but from what I've read online its bad practice to use static datatypes.
public class Beta {
public static void main(String[] args) {
Player p1 = new Player("Test");
Shop s1 = new Shop();
p1.setMoney(100);
s1.clerk(p1.getMoney());
}
}
public class Player {
private int money;
private String name;
public Player(String name) {
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int x) {
this.money +=x;
}
}
public class Shop {
private int money;
public void clerk(int x) {
this.money = x;
if (this.money >= total) {
question4 = false;
System.out.println("Your purchase was successful!");
if (blue > 0) {
this.addInventory("Blue", blue);
}
if (red > 0) {
this.addInventory("Red", red);
}
if (green > 0) {
this.addInventory("Green", green);
}
}
else {
question4 = false;
System.out.println("Sorry you cant afford that!");
}
}
}
}
So I cut down my code to show you only the essential parts.
What I want to do is access p1:s money variable from the player class from within the Shop class.
So far I have been passing the variable when calling it from main. Is this the only option I have or can it be accessed in any other way ?
Any help would be much appreciated!
I believe the option that follows Object-Oriented Programming principles best is to pass the actual Player in as an argument, instead of just the money.
Basically, passing just the player's money in instead of the player themselves is like just handing your wallet over to the cashier. You wouldn't do that, right?
This way, the clerk can ask the customer if they have enough money by calling player.getMoney(), and the customer can tell them the answer.
After making the purchase, the player can remove the money from their wallet themselves when the clerk asks them to via player.setMoney().
Now, you asked in a comment about "passing the actual player as an argument without creating a new object of the player class." Java passes arguments by value, and all objects' values are simply the address that hold the information for that particular instance.
So for Player p1 in Beta, let's pretend all of p1's information is stored in a block starting at...let's say, address 21343. In this case, the variable p1 only contains that single number, 21343.
Since Java passes by value, then when you call s1.clerk(Player player), the player variable will also contain 21343. Since it's editing the items contained at the same address, you've essentially passed on p1 itself instead of creating a new Player. In short, the clerk and the main method work with the same object.
The fact that Java passes by value is also why passing just the player's money in doesn't adjust it automatically: The money is an int rather than an object. Since it's an int, when you pass it to the clerk, you're just saying "Hey, clerk, this is the amount of money being worked with." But the clerk has no idea who the money belongs to, so while it can take money, or even give it some, it's essentially just setting it down on the counter, and it's the responsibility of the player to pick it up from there when they're done. By passing in the player instead, the clerk knows who the money belongs to because it's actually asking the player how much money they have.
Another potential solution would be to make p1 and s1 static variables in the Beta class. It'd look something like this:
public class Player
{
public static Player p1;
public static Shop s1;
public static void main(String[] args)
{
p1 = new Player("Test");
s1 = new Shop();
p1.setMoney(100);
s1.clerk(p1.getMoney());
}
}
From there, you'd import the Beta class in Shop, then call Beta.p1 in Shop to access p1.
Hope this helps!
play.java: https://pastebin.com/4bzfE76z
values.java: https://pastebin.com/6mnUzKyA
player.java: https://pastebin.com/qiFymMF6
stats.java: https://pastebin.com/P24AUpXV
I have a method called start in play.java with object parameters. The objects were originally declared in values.java inside the sValues method. I want to call the method start to the main method of play.java but I'm not sure what to write inside the parameters of the call.
Inside values.java:
player user = new player ();
user.setP_Name (username);
user.setP_ATK (atk);
user.setP_HP (hp);
stats[] enemies = new stats [3];
enemies [1] = new stats ();
enemies [1] = gob;
enemies [1].getName ();
enemies [1].getHP ();
enemies [1].getATK ();
enemies [1].getMANA ();
enemies [2] = new stats ();
enemies [2] = orc;
enemies [2].getName ();
enemies [2].getHP ();
enemies [2].getATK ();
enemies [2].getMANA ();
Inside play.java, I use the objects like this:
System.out.println ("Hitpoints[HP]: " + enemies [i].getHP ());
and it works great because I included these two objects into the parameter of the method:
public static void start (player user, stats[] enemies)
However, whenever I want to call start in the main method for it to do the things I want it to, it gives me errors. This is how I've been trying to call it:
public static void main (String[] args)
{ //main method
start(player, stats);
} //main method
Am I doing something wrong? Any help appreciated. I'll gladly add more information if needed. New to coding and not sure what specific details need to be provided.
My errors:
{ //main method
player player = new player();
start(player, stats);
} //main method
Error on: start(player, stats);
Cannot find symbol. Symbol: variable stats. Location: class play.
This error is given when I hover over "stats" when using netbeans.
The main method is the entry point of your program. You have not instantiated anything else yet so there are no objects to pass into your start method.
You might need to give us more of your code, but you might need to try something like this first - and I this is making a lot of assumptions about your code
public static void main (String[] args)
{ //main method
Player player = new Player(); // This is an instance of your Player class
// and initialize your stats array.
Values v = new Values();
start(player, stats);
} //main method
Also providing the error you are getting may help also.
EDIT
After reviewing your code I can see some problems. In your Values class you have the method sValues which creates the enemies as you said, however they stats[] that you created in that method only has the scope of that method, so when that method is finished, the enemies you created have now disappeared.
You also have a lot of static reference - this is bad practice and you need to remove as much as possible. To do this you can change something like
Values.sValues();
to
Values v = new Values(); // in the constructor call what you need to
v.sValues();
You need to think about where you are going to store your enemies stats array. You could move it to the top of your Values class and add a getter for it then your code could look like this
Values.java
public class values {
public static String clear = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
public static String username;
public static int atk = 1;
public static int hp = 10;
private stats[] enemies;
// .. your other code
public void sValues () // this method should not be static
{ //sValue method
// .. other code
enemies = new stats [3]; // Remove the declaration at the start of this line
// .. other code
}
public stats[] getEnemies()
{
return enemies;
}
Play.java
public static void main (String[] args)
{
// Create a player
player player = new player("Steve", 10, 10);
// Initialise your values
Values v = new Values();
// create the enemies (this could be done in your values constructor)
v.sValues();
// Start with these enemies
start(player, v.getEnemies());
}
Seems to me you have to create an instance of values.java and then get the player and stats objects from there to pass on to the main method. where are player, stats being declared in the play.java class?
try:
{
player player = new player();
stats[] stats = new stats[5];
start(player, stats);
} //main method
and initialize stats array with desired values
I have a method createGame on Server which create an instance of a game. What i want is to create another instance of the game for differents clients, but when i create another instance of the game, the first game created does not work anymore.
Here is the code:
private void createGame(){
gameThread.add(new GameThread(playerList, controllers.get(controllerNumber), controllers.get(controllerNumber)));
gameThread.get(gameNumber).start();
//just to shift the array of game
gameNumber++;
//shift the array of controller
controllerNumber++;
clientCounter = 0;
playerList.clear();
controllers.add(new ControllerServerSide());
}
Why I can't play two games at the same time, if each one is on a different thread?
EDIT:
GameThread
public class GameThread extends Thread{
private Settings settings;
private Game game;
private static int gamesActive = 0;
public GameThread(ArrayList<Player> playerList, Observer observer, ObservableInput controllerServer){
ArrayList<Player> newPlayerList = new ArrayList<>();
int size = playerList.size();
for(int i = 0; i < size; i++){
newPlayerList.add(playerList.remove(0));
}
settings = new Settings("src/main/java/it/polimi/ingsw/ps05/gamelogic/mappa.xml", newPlayerList);
game = new Game(settings, gamesActive++, observer, controllerServer);
game.init();
}
public void run(){
game.play();
}
}
From your code it isn't clear what are the members or what they do.. it's really hard to understand what your code does..
But I'll give it a shot:
Try and see if one of the new threads change the same objects as the old game thread.
Or - and I think that might be the problem - you clear the array/list of players and controllers - which both games use.. so the first game works fine but the second clean those list/arrays and destrying what's in there - so your first game stop working.. check it out.
private void createGame(){
gameThread.add(new GameThread(playerList, controllers.get(controllerNumber), controllers.get(controllerNumber)));
gameThread.get(gameNumber).start();
//just to shift the array of game
gameNumber++;
//shift the array of controller
controllerNumber++;
clientCounter = 0;
playerList.clear();
controllers.add(new ControllerServerSide());
I do not know how to do the borrowHolding() in the Library Menu I have to create.
So the purpose of the borrowHolding() is for members to be able to borrow books or videos.
This is a just a sample data of the array:
member[0] = new StandardMember("ID", "Name");
member[1] = new PremiumMember("ID", "Name");
holding[0] = new Book("ID", "Title");
holding[1] = new Video("ID", "Title", loanFee);
This is the borrowHolding() method in the TestLibrary class: (the array is in the TestLibrary class too)
public static void borrowHolding(){
String option;
option = input.next();
do{
Scanner scan = new Scanner(System.in);
int tempId = 0;
System.out.println("Enter your ID: ");
String searchID = scan.next();
for(int i = 0; i < member.length; i++){
if(member[i].getID().equals(searchID)){
tempId = i;
}
}
So for the method, I tried to write a code that will search through the array to find the memberID that wants to borrow. It is not completed yet because I believe I am not doing it correctly
There is a Member class that contains
public class Member{
public Holding[] getCurrentHoldings(){
}
}
from the name of the method, it is used to store the holdings of the members that borrowed. So if member 1 borrows a book, that book will be stored inside the array, i think. I was thinking of using an ArrayList for this method, but not sure if it would make sense.
To borrow a book or video, there are certain conditions to be able to borrow, but I do not know how to implement this into the borrowHolding(). One of the condition are in the Holding class.
public class Holding{
public boolean borrowHolding(){
if(status == true && isOnLoan() == false)
borrowDate = newDateTime(); //this is to get the time when the book or video is borrowed
return true;
}else
return false;
}
}
And there is another condition in the Member class is that the Member must have enough credit to borrow. A book loan fee will cost $10 and a video will vary from $4 or $6.
I think I wrote a few information that is not needed but I guess its better than less information.
My problem is what do I do to the borrowHolding() method in the LibraryMenu? how do I make that if a member wants to borrow a holding, the holding will go under the member's array in the member class
public class Member{
public Holding[] getCurrentHoldings(){
}
}
with the condition from the holding class if it is met, and while executing the borrowHolding method, the method from the member class will be able to subtract the member credit by the loan fee from the book or video. is it possible?
public class Member{
private int credit = 30;
public int calculateRemainingCredit(){
credit = credit - //(the loan fee from the book or video class)
}
}
If your intentions are to add a holding to the member class then this is possible. I would suggest adding an ArrayList of Holding's rather than a regular array because it seems as if the size is going to be constantly changing.
public class Member{
private ArrayList<Holding> currentholdings; // you may need to import the arraylist
private int credit;
public void init(){ // goes in constructor
currentholdings = new ArrayList<Holding>();
credit=0;
}
public void addHolding(Holding newholding){ // adds a new holding to the members array
currentholdings.add(newholding);
credit-=newholding.getFee(); // will need to add a fee variable to the holding class;
}
}
And as for checking to see whether or not the member has enough "credit", that can be done in the borrowHolding() method right after you identify the index of the array. I would just recommend adding a parameter of the member to the borrowHolding() method so you can easily access the variables from that member.
if(member[i].getID().equals(searchID)){
tempId = i;
int tempHolding; // index of whatever holding you wanted (could get this from the scanner)
if (holding[tempHolding].borrowHolding(member[tempId])){ // check status
member[tempId].addHolding(holding[tempHolding]); // they have passed the req. so you can add the holding
}
break;
}
Hope this answered your question.
I'm new to Java, and need help. I have been asked to write a program that rolls dice and determines the chance of the player to get two "1s" on the top face of the dice. I have different functions such as role(), getTopFace() etc. I want to be get what the number on the dice is using these functions, but don't know how to call them in my main function. Here's my code:
import javax.swing.JOptionPane;
import java.util.Random;
public class SnakeEyes {
private final int sides;
private int topFace;
public static void main(String[]args)
{
String numberSides;
int n;
numberSides=JOptionPane.showInputDialog("Please enter the number of sides on the dice:");
n = Integer.parseInt ( numberSides);
int[]die=new int[n];
for (int index=0; index<n;index++)
{
die[index]=index+1;
}
//Here is where I want to get information from my functions and calculate the ods of getting two 1's.
}
public void Die(int n)
{
if(n>0)
{
int sides=n;
topFace=(int)(Math.random()*sides)+1;
}
else{
JOptionPane.showMessageDialog(null, " Die : precondition voliated");
}
}
public int getTopFace(int topFace)
{
return topFace;
}
public int role(int[] die)
{
topFace=(int)(Math.random()*sides)+1;
return topFace;
}
}
Make an object of your class SnakeEyes in your main method, and call the required functions using that object.
Example:
SnakeEyes diceObj = new SnakeEyes();
int topFace = diceObj.role(n,....);
If you want to call this functions from main this functions must be "static", because main its a static function and static function can only call other static functions.
But... this is a very ugly design for a java program, before jumping to write java code you need to understand at least a little about object orientation. For example, why you can't call a non-static function from a static function?, the answer of this question requires knowledge about object orientation and its a knowledge you need if you want to write serious java code.