我目前正在从事基于文本的'rpg'游戏。我做了两堂课,首先应该模拟从一个城镇到另一个城镇的道路,这样做可能会遇到敌人。战斗逻辑被放置在另一堂课中,当玩家死亡时,我称之为的方法应该从上一个保存或创建新角色中加载游戏,而且效果很好,但是即使播放器死亡的道路也是继续而不是打破循环。Leavetown班级看起来像这样:
public class WorldMap {
boolean running=true;
public void leaveTown(Character character){
EnemyFactory factory = new EnemyFactory();
PerformAtack atack = new PerformAtack();
StringBuilder sb = new StringBuilder();
Random random = new Random();
int progress = 0;
while(running && progress!=100){
try {
System.out.print(sb.append("#"));
System.out.println(progress+"%");
if (random.nextDouble() * 10 < 2) {
atack.performFight(character,factory.generateRandomEnemy());
}
Thread.sleep(500);
}catch(Exception ex){}
progress = progress+5;
}
}
}
如您所见,我正在使用循环时,该循环应该在设置为false或道路完成时会破裂。当角色死亡时,我称呼方法battleLost
:
private void battleLost(Character character){
WorldMap map = new WorldMap();
System.out.println("You are dead.nWould you like to try AGAIN or LOAD your last save");
System.out.println("Please type AGAIN or LOAD");
while(true) {
String choice = sc.nextLine().toUpperCase();
if (choice.equals("AGAIN")) {
map.running = false;
System.out.println("Create new character?");
break;
} else if (choice.equals("LOAD")) {
map.running = false;
save.readFromFile();
break;
} else
System.out.println("Try again.");
}
}
此方法将类世界图中的运行变量设置为false,但是while
循环是继续而不是断裂。我知道问题可能与以错误的方式使用map.running = false;
有关。我很高兴有人可以解释我应该如何解决这个问题。
boolean running=true;
此变量应为Character
类的一部分。
然后,您的while
看起来像:
while(character.isRunning() && progress!=100)
,在performFight
中,您可以在死亡时将其更新为false
。
我猜battleLost()
属于PerformAtack
类。因此,battleLost()
内部的本地变量map
不会影响控制道路的对象。
您可以做两件事:
-
使
running
静态(和public),然后您可以通过类似WolrdMap.runnning = false
的类名来引用它,但是如果您决定并行执行操作(例如,多个线程),则此解决方案会出现问题。 REMMEBER:静态数据几乎总是多线程设计的陷阱! -
一个更好的解决方案是使
atack.performFight
返回布尔值并将该值分配给running
var:running = atack.performFight(...
这在线程安全方面是更好的设计,但是您必须从battleLost()
传播Boolean值(IT也将不得不将布尔值)返回" perform -fight()",等等
好吧,将可变boolean running=true;
的访问修饰符更改为 public static boolean running=true;
这样做后,您可以将此变量更改为false而不创建实例以打破循环,做类似的事情
private void battleLost(Character character){
WorldMap map = new WorldMap();
System.out.println("You are dead.nWould you like to try AGAIN or LOAD your last save");
System.out.println("Please type AGAIN or LOAD");
while(WorldMap.running) {
String choice = sc.nextLine().toUpperCase();
if (choice.equals("AGAIN")) {
map.running = false;
System.out.println("Create new character?");
break;
} else if (choice.equals("LOAD")) {
map.running = false;
save.readFromFile();
break;
} else
System.out.println("Try again.");
}
public void breakTheLoop(){
WorldMap.running=false;
}
由于静态是一个类变量,因此在所有类之间将共享其值