Click here to Skip to main content
15,888,401 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, so I have a combat system that uses weapons with different damages in my game. I can equip the weapons and it says that the damage is correct but I have a test that says it is null which is a problem. I have a few different classes here that could effect things.

Here is the MainGame class that handles most things:

package TextAdvenureGame;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

public class MainGame {
	
	//Code to go from room to room
	static HashMap<String,Room> roomList = new HashMap<String, Room>();
	public static String currentRoom;
	static PlayerStats player;
	static boolean isPlaying = true;
	
	//Actual start
	public static void main(String[] args) {
		 player = new PlayerStats(currentRoom);
	    
	    // set the starting room
		CombatTest combatTest = new CombatTest();
		setup(); 
		    
		System.out.println("Welcome");
		lookAtRoom(true);		
		
		while(isPlaying) {
			String command = getCommand();
			String word1 = command.split(" ")[0];		 
			
			switch(word1.toLowerCase()) {
			case "n": case "s": case "w": case "e": case "u": case "d":
			case "north": case "south": case "west": case "east": case "up": case "down":
				moveToRoom(word1.charAt(0), player, combatTest);
				break;
			case "i": case "inventory":
				showInventory(player);
				break;
			case "look":
				System.out.println("problem");
				lookAtRoom(true);
				break;
			case "hp": case "h":
				System.out.println("Your health is: " + player.getHealth());
				break;
			case "equip":
				 String itemName = command.substring(6); // assumes "equip " is 6 characters long
				    boolean found = false;
				    System.out.println("Item name: " + itemName);
				    for (Item item : player.getInventory()) {
				        if (item.getName().equalsIgnoreCase(itemName)) {
				            player.equipItem(item);
				            System.out.println("Equipped " + item.getName());
				            found = true;
				            break;
				        }
				    }
				    if (!found) {
				        System.out.println("Item not found in inventory");
				    }
			    break;
			case "take":
			    if (command.split(" ").length < 2) {
			        System.out.println("What do you want to take?");
			    } else {
			        String itemNameTwo = command.split(" ")[1];
			        Room currentRoom = roomList.get(player.getLocation());
			        String result = takeItem(itemNameTwo, player, currentRoom);
			        System.out.println(result);
			    }
			    break;
			case "search":
			    String[] words = command.split(" ");
			    if (words.length > 2 && words[words.length-2].equalsIgnoreCase("under") && words[words.length-1].equalsIgnoreCase("rock")) {
			        Room currentRoom = roomList.get(player.getLocation());

			        // Find the rock object in the current room's objects list
			        Objects rockObject = null;
			        ArrayList<Objects> objectsList = Objects.getObjectList(currentRoom);
			        for (Objects obj : objectsList) {
			            if (obj.getName().equalsIgnoreCase("rock")) {
			                rockObject = obj;
			                break;
			            }
			        }

			        if (rockObject != null) {
			            // Set the "interactedWith" flag for the rock object to true
			            rockObject.setInteractedWith(true);
			            System.out.println("You looked under the rock. You find some coins there");
			        } else {
			            System.out.println("There is no rock to look under.");
			        }
			    } else {
			        System.out.println("You search the area.");
			    }
			    break;
			default: 
                System.out.println("Sorry, I don't understand that command");
                lookAtRoom(true);
                break;
			}
		}
	}
	
	//Taking items
	public static String takeItem(String itemName, PlayerStats playerStats, Room currentRoom) {
	    if (currentRoom == null) {
	        System.out.println("The player is not in a room!");
	        return "";
	    }
	    Item item = currentRoom.getItem(itemName);
	    if (item == null) {
	        return "There is no " + itemName + " in the " + currentRoom.getTitle() + ".";
	    } else {
	        playerStats.addItem(item);
	        currentRoom.getItems().remove(item);
	        return "You have taken the " + itemName + " from the " + currentRoom.getTitle() + ".";
	    }
	}

	//This will crash if you move to a room that does not exist in the hashmap.
	public static void moveToRoom(char dir, PlayerStats playerStats, CombatTest combatTest) {
	    Room currentRoomObject = roomList.get(currentRoom);
	    String newRoom = currentRoomObject.getExit(dir);

	    if (newRoom.length() == 0) {
	        System.out.println("You can't go that way");
	        lookAtRoom(true);
	        return;
	    }

	    ArrayList<Enemy> enemies = currentRoomObject.getEnemies();
	
	    //Dirty Path Bandit Encounter
	   if (newRoom.equals("dirty") && !enemies.isEmpty()) {
	        System.out.println("As you step onto the dirty path, three bandits jump out from the shadows and attack you!");
	        for (int i = 0; i < enemies.size(); i++) {
	            combatTest.run(enemies.get(i));
	        }
	        for (int i = enemies.size() - 1; i >= 0; i--) {
	            if (enemies.get(i).getHealth() <= 0) {
	                enemies.remove(i);
	            }
	        }
	        if (enemies.isEmpty()) {
	            System.out.println("You have defeated all the bandits in this area! You can continue on your journey!");
	        }
	    }
	   
	   //Castle path bandit encounter
	   if (newRoom.equals("castle") && !enemies.isEmpty()) {
	        System.out.println("As you step onto the castle path, 3 bandits in black armour and cloaks jump out and attack you!!");
	        for (int i = 0; i < enemies.size(); i++) {
	            combatTest.run(enemies.get(i));
	        }
	        for (int i = enemies.size() - 1; i >= 0; i--) {
	            if (enemies.get(i).getHealth() <= 0) {
	                enemies.remove(i);
	            }
	        }
	        if (enemies.isEmpty()) {
	            System.out.println("You have defeated all the strange guards in this area! You can continue on your journey!");
	        }
	    }
	   
	   //Goblin encounter
	    else if (newRoom.equals("cityGate") && !enemies.isEmpty()) {
	        System.out.println("As you leave the clearing, three goblins jump out from the bushes and attack you!");
	        for (int i = 0; i < enemies.size(); i++) {
	            combatTest.run(enemies.get(i));
	        }
	        for (int i = enemies.size() - 1; i >= 0; i--) {
	            if (enemies.get(i).getHealth() <= 0) {
	                enemies.remove(i);
	            }
	        }
	        if (enemies.isEmpty()) {
	            System.out.println("You have defeated all the goblins in your path! You can continue on your journey!");
	        }
	    }
	   
	   //The Torturer encounter
	    else if (newRoom.equals("torturer") && !enemies.isEmpty()) {
	        System.out.println("As you enter the room you see a man in a hood injecting something into a screaming man. The hooded man then says \"Hmmm, no not this one. Too painful. someone will hear the king scream when he dies.\" The man then turns around and notices you, as the screaming man behind him dies. The strange man then says \"Are you someone sent by the king, or just an unlucky wanderer? No matter, you will die either way!\" He then pulls out two poison covered knives and attacks you!");
	        for (int i = 0; i < enemies.size(); i++) {
	            combatTest.run(enemies.get(i));
	        }
	        for (int i = enemies.size() - 1; i >= 0; i--) {
	            if (enemies.get(i).getHealth() <= 0) {
	                enemies.remove(i);
	            }
	        }
	        if (enemies.isEmpty()) {
	        	System.out.println(" ");
	            System.out.println("As the Assassin falls he says \"No, no, no! I can't die here! That damn king will still live! No!\" and with that he falls to the ground dead.");
	            System.out.println("As you stand over your defeated enemy you realize that you just stopped a plot to assassinate the king, you will surely get some sort of reward!");
	            System.out.println("You got the good ending, with the plot to assassinate the king foiled, the king continues to reign over a peaceful era which leads into a golden age for the kingdom. You are able to gain the riches and position you wanted from the king.");
	            System.exit(0);
	        }
	    }
	   
	 //The Torturer encounter
	    else if (newRoom.equals("assassin") && !enemies.isEmpty()) {
	        System.out.println("As you enter the room you see the king with his knife slit, and a hooded man with a knife standing above him, who then throws two knives and kills the guards you were talking with, then lunges at you!");
	        for (int i = 0; i < enemies.size(); i++) {
	            combatTest.run(enemies.get(i));
	        }
	        for (int i = enemies.size() - 1; i >= 0; i--) {
	            if (enemies.get(i).getHealth() <= 0) {
	                enemies.remove(i);
	            }
	        }
	        if (enemies.isEmpty()) {
	        	System.out.println(" ");
	            System.out.println("As the Assassin falls he says \"It matters notif I fall. I accomlished my mission, the king is dead. Ha, Ha, *cough*, haaaaaah. \"");
	            System.out.println("You stand above your slain foe, but you are filled with grief as you realize you failed in your task.");
	            System.out.println("You got the bad ending, with the King dead and with no immediate successor the kingdom falls into anarchy. Unbenownst to all, a new order rises in the shadows, planting the seeds to take power.");
	            System.exit(0);
	        }
	    }
	   
	   //Going to the new room
	    currentRoom = newRoom;
	    playerStats.setLocation( newRoom ); 
	    lookAtRoom(true);
	}
		
//looking at the rooms
	private static void lookAtRoom(boolean b) {
	    Room rm = roomList.get(currentRoom);
	    System.out.println("\n== " + rm.getTitle() + " ==");
	    System.out.println(rm.getDesc());
	}
		

	private static void showInventory(PlayerStats playerStats) {
	    ArrayList<Item> inventory = playerStats.getInventory();
	    if (inventory.isEmpty()) {
	        System.out.println("Your inventory is empty");
	    } else {
	        System.out.println("Inventory:");
	        for (Item item : inventory) {
	            System.out.println("- " + item.getName() +": "+ item.getDescription());
	        }
	        if (playerStats.getEquippedWeapon() == null) {
	            System.out.println("Equipped weapon: None");
	        } else {
	            System.out.println("Equipped weapon: " + playerStats.getEquippedWeapon().getName());
	        }
	    }
	    lookAtRoom(true);
	}

	static Scanner sc = new Scanner(System.in);
	static String getCommand() {
		System.out.print("=> ");		
		String text = sc.nextLine();
		System.out.println(" ");
		if (text.length() == 0) text = "qwerty"; //default command		
		return text;
	}
	
	static void setup() {
		Room.setupRooms(roomList);
	    currentRoom = "clearing"; //where you start
		player.setLocation(currentRoom);
	}
  }


Here is the Room class that deals with moving from room to room and adding in items, objects, and enemies:

age TextAdvenureGame;

import java.util.ArrayList;
import java.util.HashMap;

class Room {

	private String title;
	private String description;	
	private String N,S,E,W;
	private ArrayList<Item> itemList = new ArrayList<Item>();
	public ArrayList<Enemy> enemyList = new ArrayList<Enemy>(); // added for enemies in the room
    private ArrayList<Objects> objectsList = new ArrayList<Objects>();

 //adding enemies
	 public ArrayList<Enemy> getEnemyList() {
	        return enemyList;
	    }
	 
//adding objects	
	 public ArrayList<Objects> getObjectsList() {
		    return objectsList;
		}
	 
	//Adding objects
	 public void addObject(Objects obj) {
		    objectsList.add(obj);
		}
	 
	 public Objects getObjectByName(String name) {
		    for (Objects obj : objectsList) {
		        if (obj.getName().equalsIgnoreCase(name)) {
		            return obj;
		        }
		    }
		    return null; // if object not found in room
		}
	 
	 //Itemlist thing
	 public void addItem(Item item) {
	        itemList.add(item);
	    }
	 
	 public Item getItem(String itemName) {
		    for (Item item : itemList) {
		        if (item.getName().equals(itemName)) {
		            return item;
		        }
		    }
		    return null;
		}

	    public ArrayList<Item> getItems() {
	        return itemList;
	    }
	 
	Room(String t, String d) {
		title = t;
		description = d;
	}
	
	private void setExits(String N, String S, String W, String E) {
		this.N = N;
		this.S = S;
		this.W = W;
		this.E = E;		
	}
	
	String getExit(char c) {
		switch (c) {
		case 'n': return this.N;
		case 's': return this.S;
		case 'w': return this.W;
		case 'e': return this.E;
		default: return null;
		}
	}
	
	String getTitle() {return title;}
	String getDesc() {return description;}
	
	public ArrayList<Enemy> getEnemies() {
	    return this.enemyList;
	}
	
	public static Room getRoom(String name, ArrayList<Room> roomList) {
	    for (Room room : roomList) {
	        if (room.getTitle().equals(name)) {
	            return room;
	        }
	    }
	    return null;
	}
	
	// done at the beginning of the game
	static void setupRooms(HashMap <String, Room> roomList) {
		
		//Going north into the city routes
		Room r = new Room("Clearing", "You are in a small clearing in a" +
	" forest. You hear birds singing. You can also hear faint voices to the north of you. You also notice a rock with a pouch under it and a dagger lying on the ground.");
		r.enemyList.add(new Goblin()); // add three goblins to the clearing
		r.enemyList.add(new Goblin());
		r.enemyList.add(new Goblin());
		
		r.addObject(new Objects("rock", false));
		
		r.addItem(new Item("dagger", "A sturdy dagger that does 5 damage", 1, 5));
		r.addItem(new Item("coins", "Gold coins that can be traded for goods", 5, 0));
		
		r.setExits("cityGate", "", "", "");
		roomList.put("clearing", r);


Here is the PlayerStats class that deals with the player and also importantly for this question equipping weapons and returning damage. Through my tests, the item is getting equipped I think it just isnt returning the damage I think.

package TextAdvenureGame;

import java.util.ArrayList;

class PlayerStats {
    private int maxHealth = 20;
    private int health;
    private int baseDamage;
    private Item equippedWeapon;
    private String location;
    private ArrayList<Item> inventory;

    public PlayerStats(String location) {
        this.baseDamage = 1;
        this.health = maxHealth;
        this.inventory = new ArrayList<Item>();
        this.setLocation(location);
    }

    public void equipItem(Item item) {
    	    System.out.println("Equipping weapon: " + item.getName());
    	    if (item.getDamage() > 0) {
    	        this.equippedWeapon = item;
    	        System.out.println("Equipped weapon: " + equippedWeapon.getName());
    	        this.baseDamage = item.getDamage();
    	        System.out.println("Base damage set to: " + baseDamage);
    	    } else {
    	        System.out.println("Item is not a weapon.");
    	    }
    	}

    public int getDamage() {
        if (this.equippedWeapon == null) {
            System.out.println("Equipped weapon is null");
        } else {
            System.out.println("Equipped weapon is not null");
        }
        
        int totalDamage = this.baseDamage;
        if (this.equippedWeapon != null) {
            totalDamage += this.equippedWeapon.getDamage();
        }
        
        System.out.println("Total damage is: " + totalDamage);
        return totalDamage;
    }
    
    public int getHealth() {
        return health;
    }

    public boolean isAlive() {
        return health > 0;
    }

    public void takeDamage(int damage) {
        health -= damage;
        if (health < 0) {
            health = 0;
        }
    }

    public ArrayList<Item> getInventory() {
    	System.out.println("Inventory: " + inventory);
        return inventory;
    }

    public void setInventory(ArrayList<Item> inventory) {
        this.inventory = inventory;
    }

    public void addItem(Item item) {
        inventory.add(item);
    }

    public void setLocation(String currentRoom) {
        this.location = currentRoom;
    }

    public String getLocation() {
        return location;
    }
    
    public Item getEquippedWeapon() {
        return equippedWeapon;
    }


Here is the CombatTest class that could also affect it:

package TextAdvenureGame;

import java.util.Scanner;

public class CombatTest {
    private CombatSystem combatSystem;
    private PlayerStats playerStats;
    
    private Enemy enemy;

    public CombatTest() {
        this.combatSystem = new CombatSystem();
        this.playerStats = new PlayerStats(null);
        this.enemy = new Goblin();
        this.enemy = new Bandit();
    }

    public void run(Enemy enemy) {
    	while (playerStats.isAlive() && enemy.isAlive()) {
                          
        	System.out.println("Please choose to attack or use an item: ");
    		Scanner stringScanner = new Scanner(System.in);
    		String input = stringScanner.nextLine();
    		System.out.println(" ");		
			
   if(input.equalsIgnoreCase("attack") || input.equalsIgnoreCase("a")) {
           boolean playerHit = combatSystem.attack();
           boolean enemyHit = combatSystem.attack();

           if (playerHit == true) {
        	    int damage = 0;
        	    if (playerStats.getEquippedWeapon() != null) {
        	        damage = playerStats.getEquippedWeapon().getDamage();
        	    }
        	    damage += playerStats.getDamage(); // use getTotalDamage instead of getDamage
        	    enemy.takeDamage(damage);
        	    System.out.println("You hit the " + enemy.getName() + " for " + damage + " damage!");
        	}
            else {
            	System.out.println("You missed!");
            }

            if (enemyHit == true) {
                int damage = enemy.getDamage();
                playerStats.takeDamage(damage);
                System.out.println("The " + enemy.getName() + " hits you for " + damage + " damage!");
                System.out.println("Your Health is: " + playerStats.getHealth());
                
            }
            else {
            	System.out.println("The " + enemy.getName() + " missed you!");
            	System.out.println("Your Health is: " + playerStats.getHealth());
          }
        }
      }
        
        if (playerStats.isAlive()) {
            System.out.println("You defeated the " + enemy.getName() + "!");
        } else {
            System.out.println("You were defeated by the " + enemy.getName() + "'s !");
            System.out.println("Game Over");
            System.exit(0);
        }
    } 
}


What I have tried:

I have tried to change the getDamage method many times and have also tried to change the equipWeapon method.

This is the response I get when I play:

Welcome

== Clearing ==
You are in a small clearing in a forest. You hear birds singing. You can also hear faint voices to the north of you. You also notice a rock with a pouch under it and a dagger lying on the ground.
=> take dagger

You have taken the dagger from the Clearing.
=> equip dagger

Item name: dagger
Inventory: [TextAdvenureGame.Item@67b64c45]
Equipping weapon: dagger
Equipped weapon: dagger
Base damage set to: 5
Equipped dagger
=> n

As you leave the clearing, three goblins jump out from the bushes and attack you!
Please choose to attack or use an item:
a

Equipped weapon is null
Total damage is: 1
You hit the Goblin for 1 damage!
The Goblin missed you!
Your Health is: 20
You defeated the Goblin!
Please choose to attack or use an item:

Thank you for any responses.
Posted
Updated 19-Apr-23 6:35am
Comments
[no name] 18-Apr-23 23:51pm    
You start with the "damage method" (wherever that is ... Is it gettng called? ... what is it returning?) and work your way out; not the other way ... which is what a code dump amounts to.
Richard MacCutchan 19-Apr-23 3:33am    
"I have a test that says it is null which is a problem"
So somewhere in all that code you have a test which does something but maybe not correctly. And you expect us to guess what and where.

1 solution

I think what's going on here is that in your MainGame class, main method you are creating a new PlayerStats object called 'player'. You also create a new CombatTest object called 'combatTest'.

In the CombatTest class the constructor creates a new PlayerStats object called 'playerStats'. This is a different object from the one created on MainGame.

Back in MainGame is where you equip its 'player' object with a dagger. When you get around to attacking the Goblins your're in 'combatTest' with an unequipped 'playerStats' object.

I think when you create the combatTest object on MainGame you need to pass the already created 'player' object instead of creating an entirely new one.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900