嗨,就像我说的,我正在Java做一个文本冒险游戏,出于某种原因,除了让我在房间里可以拿起任何物品的方法之外,其他一切都有效。它认为我不在房间里,返回一个空值,即使我已经初始化了起始值。也很抱歉,我有多个类,问题可能出在哪里,我不会问我是否有任何关于如何修复它的想法。
这是我的主要游戏类,其中添加了获取项目的方法和函数:
//Code to go from room to room
static HashMap<String,Room> roomList = new HashMap<String, Room>();
static String currentRoom;
static PlayerStats player;
static boolean isPlaying = true;
//Actual start
public static void main(String[] args) {
PlayerStats playerStats = new PlayerStats();
CombatTest combatTest = new CombatTest();
setup();
System.out.println("Welcome");
lookAtRoom(true);
while(isPlaying) {
String command = getCommand().toLowerCase();
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), playerStats, combatTest);
break;
case "i": case "inventory":
showInventory(playerStats);
break;
case "look":
lookAtRoom(true);
break;
case "hp": case "h":
System.out.println("Your health is: " + playerStats.getHealth());
break;
case "take":
if(command.split(" ").length < 2) {
System.out.println("What do you want to take?");
} else {
String itemName = command.split(" ")[1];
Room currentRoom = playerStats.getLocation();
String result = takeItem(itemName, playerStats, currentRoom);
System.out.println(result);
}
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 this room.";
} else {
playerStats.addItem(item);
currentRoom.getItems().remove(item);
return "You have taken the " + itemName + ".";
}
}
//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();
//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!");
}
}
//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!");
}
}
//Going to the new room
currentRoom = 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());
}
}
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
}
}
这是房间类,处理从一个房间到另一个房间以及物品实际添加到房间的地方,现在我只有一把匕首和一些硬币在“空地”,所以我可以测试:
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
public ArrayList<Enemy> getEnemyList() {
return enemyList;
}
//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 strange rock.");
r.enemyList.add(new Goblin()); // add three goblins to the clearing
r.enemyList.add(new Goblin());
r.enemyList.add(new Goblin());
r.addItem(new Item("Coins", "Shiny gold coins that can be traded for goods", 5,
0));
r.addItem(new Item("Dagger", "A sturdy dagger that does 1 damage", 1, 1));
r.setExits("cityGate", "", "", "");
roomList.put("clearing", r);
r = new Room("City Gates", "You see the gates of a city as you" +
" approach the voices, there are guards outside the gates. You also see a
suspicious looking man at the edge of the forest to the west.");
r.setExits("market", "clearing", "susman", "");
roomList.put("cityGate", r);
//all the different shops and the market place.
r = new Room("Market Place", "When you enter the city you see a "+
"busy marketplace, to the west of you is a supplies shop," +
" to the east of you there is a weapons shop. You can see a large castle in the
distance northwards.");
r.setExits("ornate", "cityGate", "supplyMerchant", "weaponsMerchant");
roomList.put("market", r);
r = new Room("Suspicious Man", "As you approach the man he notices you and
quietly says \"Hey! Hey you! Over here!\" He motions for you to enter a forest
clearing and says \"Hello stranger! I have some... not so legally aquired items
for sale. So what're you buyin?\" ");
r.setExits("", "", "", "cityGate");
roomList.put("susman", r);
r = new Room("Weapons Merchant", "As you walk towards the weapons merachant he
says \"Welcome good sir! I have the finest weapons in the whole realm! Best
prices too! Now look around and see what you are interested in! \" ");
r.setExits("", "", "market", "");
roomList.put("weaponsMerchant", r);
r = new Room("Supplies Merchant", "As you walk towards the weapons merachant he
says \"Hello sir! I have a variety of different items for sale. Please look to
your hearts content and buy whatever your heart desires.\" ");
r.setExits("", "", "", "market");
roomList.put("supplyMerchant", r);
//Towards the castle/dungeon
r = new Room("Ornate Path", "As you walk towards the castle you walk along an
ornate path, it is made of marble and has fancy looking lanterns hanging above
to provide light. You reach a branch in the road, you can either continue north
towards the castle, or step off the main path eastward into a much less ornate,
dirty looking path. You cannot tell where the dirty looking path leads.");
r.enemyList.add(new Bandit()); // add three bandits to the clearing
r.enemyList.add(new Bandit());
r.enemyList.add(new Bandit());
r.setExits("castle", "market", "", "dirty");
roomList.put("ornate", r);
//Dungeon Route
r = new Room("Dirty Path", "As you walk along the dirty path you evntually see a
small building that has a staircase leading downwards. This is your last chance
to turn back.");
r.setExits("", "", "ornate", "dungeonEnt");
roomList.put("dirty", r);
r = new Room("Dungeon Entrance", "You enter the dungeon and see a few cells with
skeletons in them and dried blood stains on the floor, you hear voices coming
from behind a door to the south, and the hallway continues to the east.");
r.setExits("", "southDugDoor", "", "dungeon");
roomList.put("dungeonEnt", r);
r = new Room ("Southern Dungeon Door","You can hear some voices behind the door
but would have to get closer to understand, or you could go back to the main
hall.");
r.setExits("dungeonEnt", "", "", "");
roomList.put("southDugDoor", r);
r = new Room("Dungeon", "You enter the middle of the hall each side of the hall
is lined with cells with bodies and fresher looking blood in them. Ahead of you,
you can hear screams and someone talking to themselves as well, though you
cannot hear what");
r.setExits("", "", "dungeonEnt", "torturer");
roomList.put("dungeon", r);
r = new Room("Boss Room: The Torturer", "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!");
r.setExits("", "", "dungeon", "");
roomList.put("torturer", r);
//Castle Route
r = new Room("Castle Pathway", "As you walk towards the castle, you are happy
that you might finally get some work from the king. This is your last chance to
turn back.");
r.setExits("castleEnt", "ornate", "", "");
roomList.put("castle", r);
r = new Room("Castle Entrance", "As you walk up to the entrance of the castle,
you can see a large staircase and walking down the staircse towards you is an
armoured knight.");
r.setExits("throne", "", "", "");
roomList.put("castleEnt", r);
r = new Room("Boss Room: The Assassin","");
r.setExits("", "", "", "");
roomList.put("Throne", r);
}
}
这是具有位置设置器和获取器的playerStats类:
TextAdvenureGame;
import java.util.ArrayList;
public class PlayerStats {
private int baseDamage = 1;
private int health = 10;
private Weapon equippedWeapon;
private Room location;
private ArrayList<Item> inventory;
public PlayerStats() {
this.equippedWeapon = null;
this.inventory = new ArrayList<Item>();
this.location = location;
}
public void Stats(int baseDamage, int health) {
this.baseDamage = baseDamage;
this.health = health;
}
public void equipWeapon(Weapon weapon) {
this.equippedWeapon = weapon;
}
public int getDamage() {
if (equippedWeapon == null) {
return baseDamage;
} else {
return baseDamage + equippedWeapon.getDamage();
}
}
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() {
return inventory;
}
public void setInventory(ArrayList<Item> inventory) {
this.inventory = inventory;
}
public void addItem(Item item) {
inventory.add(item);
}
public void setLocation(Room currentRoom) {
this.location = currentRoom;
}
public Room getLocation() {
return location;
}
}
`
再次为冗长的编码问题道歉,但我真的没有想法。它现在正在做的是,每当我玩游戏时,它都会这样做:欢迎
==清除==你在森林里的一片小空地上。你听到鸟儿唱歌。你还能听到你北边微弱的声音。你还注意到一块奇怪的岩石。=
玩家不在房间里!
您在setUp()
中将String
类型的当前房间
初始化为清除
。
但是然后在“采取”
方法中,您将当前房间
重新声明为类型Room
,并且您使用Player
类中的位置
。
} else {
String itemName = command.split(" ")[1];
Room currentRoom = playerStats.getLocation();
String result = takeItem(itemName, playerStats, currentRoom);
System.out.println(result);
}
因此,似乎从未使用过全局位置
,并且从未初始化Player
位置变量。