重构代码以提高Yatzy游戏的效率

时间:2019-05-24 09:55:47

标签: java

我正在为2名玩家开发yatzy游戏,其中包括Fullhouse,Yatzy,一个,两个,三次等所有类别。

我已经实现了适用于2个玩家的界面,并在游戏结束时显示获胜者,但是我认为这不是有效的反馈和建议,以改善我的代码

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class YatzyUI {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the name of the first player");
        String firstPlayerName = scanner.next();
        System.out.println("Enter the name of the second player");
        String secondPlayerName = scanner.next();
        Player p1 = new Player(firstPlayerName);
        Player p2 = new Player(secondPlayerName);
        List<Player> players = new ArrayList<>();
        players.add(p1);
        players.add(p2);
        int score = 0;
        try {
            for (int i = 1; i <= 15; i++) {
                p1.firstRollDice(firstPlayerName);
                p1.secondAndThirdRollDice();
                p1.selectAndSetCategoryScore(p1.getDiceArray());
            }
        } catch (NullPointerException e) {
            System.out.println("Please enter a valid category ,the category chosen is invalid ");
            p1.selectAndSetCategoryScore(p1.getDiceArray());
        }
        try {
            for (int i = 1; i <= 15; i++) {
                p2.firstRollDice(secondPlayerName);
                p2.secondAndThirdRollDice();
                p2.selectAndSetCategoryScore(p1.getDiceArray());
            }

        } catch (NullPointerException e) {
            System.out.println("Please enter a valid category ,the category chosen is invalid ");
            p2.selectAndSetCategoryScore(p1.getDiceArray());
        }

        Collections.sort(players, new ScoreComparartor());
        Player winner = players.remove(1);
        System.out.println("Following is the winner of the game :" + winner.getPlayerName() + " with the score : " + winner.getPlayerScore());
    }
}

输出得分最高的获胜者

0 个答案:

没有答案