首页 > 解决方案 > 在简单的 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();
    }

标签: java

解决方案


推荐阅读