簡體   English   中英

Java +剪刀石頭布游戲+ OOP(?)

[英]Java + rock paper scissors game + OOP(?)

我有一個任務要做一個石頭剪刀布游戲,該游戲將允許用戶輸入“ R,P,S或Q退出”。 如果用戶輸入Q退出,則必須以百分比格式顯示獲勝和失敗。 我嘗試了涉獵繼承,但是這樣做是為了防止找不到更有效,可能更多的OOP方法。

我的問題是:是否有一種更快,更有效的編碼方式? OOP似乎可以工作,但這不是必須的。

// main method
public static void main(String[] args) 
{
    Scanner scan = new Scanner(System.in);

    // variables
    double wins = 0;
    double losses = 0;
    double draws = 0;
    double games = 0;
    Integer answer1 = null;

    boolean playing = true;

    // start of game
    while (playing) 
    {
        // main menu
        System.out.println("Input R, P, S, or Q(to quit).");
        String answer = scan.next();

        // player's move
        answer = answer.toLowerCase();

        // computer's move
        Random random = new Random();
        Integer choice = random.nextInt(3); // n-1
        String comp = choice.toString();
        System.out.println(comp);

        // converts player's move from str to int
        switch (answer)
        {
        case "r":
            answer1 = 0;
            break;
        case "p":
            answer1 = 1;
            break;
        case "s":
            answer1 = 2;
            break;
        case "q":
            System.out.println("User exit.");
            double winP = wins/games*100;
            double loseP = losses/games*100;
            double drawP = draws/games*100;

            System.out.println("Wins: " + wins);
            System.out.printf("%.2f", winP);
            System.out.println(" Percent");
            System.out.println("Losses: " + losses);
            System.out.printf("%.2f", loseP);
            System.out.println(" Percent");
            System.out.println("Draws: " + draws);
            System.out.printf("%.2f", drawP);
            System.out.println(" Percent");
            answer1 = null;
            playing = false;
            break;
        }

        // checks for conditions
        // draw
        if (playing == true) 
        {
            if (answer1 == choice)
            {
                System.out.println("Draw");
                draws++;
                games++;
            }
            // losses
            if (answer1 == 0 && choice == 1)
            {
                System.out.println("YOU LOSE! :D");
                losses++;
                games++;
            }
            if (answer1 == 1 && choice == 2)
            {
                System.out.println("YOU LOSE! :D");
                losses++;
                games++;
            }
            if (answer1 == 2 && choice == 0)
            {
                System.out.println("YOU LOSE! :D");
                losses++;
                games++;
            }
            // wins
            if (answer1 == 0 && choice == 2)
            {
                System.out.println("you win... :D");
                wins++;
                games++;
            }
            if (answer1 == 1 && choice == 0)
            {
                System.out.println("you win... :D");
                wins++;
                games++;
            }
            if (answer1 == 2 && choice == 1)
            {
                System.out.println("you win... :D");
                wins++;
                games++;
            }
        }           
    }
}

這是我做過的石頭,紙,剪刀的一個版本。 我有一個GameModel類,其中包含岩石,紙張,剪刀游戲的值,以及提供用戶界面的RockPaperScissors類。

這是用戶界面的示例:

Rock, Paper, Scissors; Enter r, p, s, or q to quit: s
We chose the same item.  Let's try again.

Rock, Paper, Scissors; Enter r, p, s, or q to quit: s
You chose Scissors, the computer chose Rock.  The computer wins.

Rock, Paper, Scissors; Enter r, p, s, or q to quit: r
You chose Rock, the computer chose Paper.  The computer wins.

Rock, Paper, Scissors; Enter r, p, s, or q to quit: s
We chose the same item.  Let's try again.

Rock, Paper, Scissors; Enter r, p, s, or q to quit: s
You chose Scissors, the computer chose Rock.  The computer wins.

Rock, Paper, Scissors; Enter r, p, s, or q to quit: q

The final score: Player 0, Computer 3, ties 2.

這是代碼:

package com.ggl.testing;

import java.util.Random;
import java.util.Scanner;

public class RockPaperScissors implements Runnable {

    private GameModel gameModel;

    private Random random;

    public static void main(String[] args) {
        new RockPaperScissors().run();
    }

    public RockPaperScissors() {
        this.random = new Random();
        this.gameModel = new GameModel();
    }

    @Override
    public void run() {
        Scanner scanner = new Scanner(System.in);

        char inputChar = getUserChoice(scanner);
        while (inputChar != gameModel.getQuitCharacter()) {
            char computerChar = generateComputerChoice();
            System.out.println(gameModel.calculateGameResult(inputChar,
                    computerChar));
            inputChar = getUserChoice(scanner);
        }

        System.out.println(gameModel.displayFinalScore());

        scanner.close();
    }

    private char getUserChoice(Scanner scanner) {
        char inputChar = ' ';

        while (gameModel.getCharacterIndex(inputChar) < 0) {
            System.out.print(gameModel.generatePrompt());
            String input = scanner.nextLine().toLowerCase();
            inputChar = input.charAt(0);
        }

        return inputChar;
    }

    private char generateComputerChoice() {
        int index = random.nextInt(gameModel.getChoicesLength() - 1);
        return gameModel.getChoiceCharacter(index);
    }

    public class GameModel {

        private final String[] CHOICES = { "Rock", "Paper", "Scissors", "Quit" };

        private int playerScore;
        private int computerScore;
        private int tieScore;

        public GameModel() {
            this.playerScore = 0;
            this.computerScore = 0;
            this.tieScore = 0;
        }

        public String getChoice(int index) {
            return CHOICES[index];
        }

        public char getChoiceCharacter(int index) {
            return CHOICES[index].toLowerCase().charAt(0);
        }

        public int getChoicesLength() {
            return CHOICES.length;
        }

        public char getQuitCharacter() {
            return getChoiceCharacter(getChoicesLength() - 1);
        }

        public int getPlayerScore() {
            return playerScore;
        }

        public int getComputerScore() {
            return computerScore;
        }

        public int getTieScore() {
            return tieScore;
        }

        public String generatePrompt() {
            StringBuilder builder = new StringBuilder();
            builder.append(CHOICES[0]);
            builder.append(", ");
            builder.append(CHOICES[1]);
            builder.append(", ");
            builder.append(CHOICES[2]);
            builder.append("; Enter ");
            builder.append(getChoiceCharacter(0));
            builder.append(", ");
            builder.append(getChoiceCharacter(1));
            builder.append(", ");
            builder.append(getChoiceCharacter(2));
            builder.append(", or ");
            builder.append(getChoiceCharacter(3));
            builder.append(" to ");
            builder.append(CHOICES[3].toLowerCase());
            builder.append(": ");

            return builder.toString();
        }

        public String calculateGameResult(char inputChar, char computerChar) {
            if (inputChar == computerChar) {
                tieScore++;
                return "We chose the same item.  Let's try again.\n";
            } else {
                int inputIndex = getCharacterIndex(inputChar);
                int computerIndex = getCharacterIndex(computerChar);
                String s = "You chose " + CHOICES[inputIndex]
                        + ", the computer chose " + CHOICES[computerIndex]
                        + ".  ";

                int testIndex = (inputIndex + 1) % (CHOICES.length - 1);
                if (testIndex == computerIndex) {
                    computerScore++;
                    return s + "The computer wins.\n";
                } else {
                    playerScore++;
                    return s + "You win.\n";
                }
            }
        }

        private int getCharacterIndex(char c) {
            for (int index = 0; index < CHOICES.length; index++) {
                if (c == getChoiceCharacter(index)) {
                    return index;
                }
            }

            return -1;
        }

        public String displayFinalScore() {
            StringBuilder builder = new StringBuilder();
            builder.append("\nThe final score: Player ");
            builder.append(playerScore);
            builder.append(", Computer ");
            builder.append(computerScore);
            builder.append(", ties ");
            builder.append(tieScore);
            builder.append(".");

            return builder.toString();
        }

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM