java - 在简单的 RPG 游戏问题中添加 do-while
问题描述
我正在构建一个简单的 RPG 游戏。我认为,我遇到了一个可以通过 do-while 循环解决的问题。下面的方法展示了玩家购买物品的方式,但目前他们只能购买一件物品。我想添加一个选项来购买多件商品,而不仅仅是一件。有一把刀、一把剑等,我想让玩家可以选择购买多个(例如一把剑和一瓶药水)。
正如我所说,我想我可以使用 do-while 循环来做到这一点,但我不确定如何实现它。仅使用 do-while 循环创建第二种方法会更好吗?并从 buyItems() 方法中调用它以使代码更具可读性?
public static void buyItems() {
player.displayPocketCoins();
System.out.println("Buy an item: \n" +
"- Press 1 for buying a knife. The cost is 5 coins.\n" +
"- Press 2 for buying a sword. The cost is 10 coins.\n" +
"- Press 3 for buying a spear. The cost is 15 coins.\n" +
"- Press 4 for buying a potion. The cost is 30 coins.");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
if(player.getCoins() >= 5) {
player.addToInventory(shopping.availableItems.get(0));
player.coinSpent(5);
System.out.println("you bought a knife.");
} else {
System.out.println("You don't have enough coins.");
buyItems();
}
break;
case 2:
if(player.getCoins() >= 10) {
player.addToInventory(shopping.availableItems.get(1));
player.coinSpent(10);
System.out.println("you bought a sword.");
} else {
System.out.println("You don't have enough coins.");
buyItems();
}
break;
case 3:
if(player.getCoins() >= 15) {
player.addToInventory(shopping.availableItems.get(2));
player.coinSpent(15);
System.out.println("you bought a spear.");
} else {
System.out.println("You don't have enough coins.");
buyItems();
}
break;
case 4:
if(player.getCoins() >= 30) {
player.addToInventory(shopping.availableItems.get(3));
player.coinSpent(30);
System.out.println("you bought a potion.");
} else {
System.out.println("You don't have enough coins.");
buyItems();
}
break;
default:
System.out.println("Invalid number, please try again.");
break;
}
player.displayRemainingCoins();
}
解决方案
推荐阅读
- mongodb - MongoError:使用 NextJs api 时拓扑被破坏
- sql - SQL - 如何根据我输入的顺序过滤条目?
- c# - AR Foundation - 在屏幕上放置 2 次触控的预制件
- javascript - 尝试在功能组件之间传递状态但出现“未定义”错误
- angular - 如何使用chartjs在一个水平堆叠的条形图中显示一段时间内的进度
- angular - Subject.next() 没有从可观察的内部触发
- c# - ReadAsync 停止代码执行,不抛出异常,Task 仍在运行
- flutter - TextField 的 Flutter Cursor 在 setState 后移动到 Position 0
- java - 测试失败:java.lang.IllegalStateException:无法加载 ApplicationContext
- python-3.x - 用 Pandas 数据框中这两个数字的总和替换 + 符号