简体   繁体   English

无法解决随机数游戏的逻辑

[英]Having trouble solving logic of random number game

I am relatively new to java programming. 我对java编程比较陌生。 I am currently working on building a mini guessing game, as a project to learn more Java. 我目前正在开发一个迷你猜谜游戏,作为一个学习更多Java的项目。 I am having some issues with the following: 我在以下方面遇到了一些问题:

Here are the 4 main things I am having trouble solving. 这是我无法解决的4个主要问题。

  • Record the answer for each user, if incorrect. 记录每个用户的答案(如果不正确)。
  • If the user was correct, skip them in subsequent rounds. 如果用户正确,则在随后的回合中跳过它们。
  • Once all players have guessed their correct number, print out the number of guesses it took for each one to guess correctly, the incorrect responses, and show a ranking of the players. 一旦所有玩家猜对了正确的数字,就可以打印出每个人正确猜对的猜测数,错误的答案并显示玩家的排名。
  • Ask if the user(s) wish to play again. 询问用户是否希望再次玩。 If so, reset all values. 如果是这样,请重置所有值。

Here are the methods that I have written; 这是我写的方法;

import java.io.*;

public class MultiPlayerRandomGame {

// this method asks how many users will be playing and returns the number of users
public static int howManyUsers() {

    System.out.println("How many users will be playing?");
    int players = IO.readInt();
    return players;
}

// this method generates and returns a random number 
public static int generateRandomNumber() {

    int randomNumber = (int) (Math.random() * 100);
    return randomNumber;
}

// this method compares user's entered guess and the generated random number then returns true/false
public static boolean compareGuess(int guess, int randomNumbers) {

    boolean isGuessCorrect = false;

    if (guess == randomNumbers) {
        System.out.println("CORRECT!");
        isGuessCorrect = true;

    } else if (guess > randomNumbers) {
        System.out.println("Too High");

    } else if (guess < randomNumbers) {
        System.out.println("Too Low");
    }

    System.out.println("test1");
    return isGuessCorrect;
} 

// this method determines whether Player N is correct or incorrect
public static boolean nextPlayer(int numOfUsers, int[] numberOfGuesses, int[] randomNumbers, int[][] numberBoard) {

    for (int n = 0; n < numOfUsers; n++) {
        int guessedNumber = numberOfGuesses[n];

        /*      if (guessedNumber == 0) {
            return false;   
        }*/

        if (numberBoard[n][guessedNumber] != randomNumbers[n]) {
            return false;
        }
    }
    return true;
}

/* this method is supposed to print out the number of guesses it took each player to guess their correct number
 * CORRECTION: change the logic of this method to printing the number of guesses for one player then
 * in the main method or wherever, make a for loop that prints out the number of guesses for each player
 */
public static void amountOfGuesses(int numOfUsers, int [] numberOfGuesses, int [][] numberBoard) {

    int n = 0;
    for ( int i = 0; i < numOfUsers; i++ ) {
        n = n + 1;
        System.out.println("Player " + n + " guessed " + numberOfGuesses[i]+ " time(s)");
    }
}

// this method determines whether the user(s) would like to play again
public static boolean playAgain(String answer) {

    boolean userWillPlayAgain;

    if (answer.compareToIgnoreCase("no") == 0) {
        userWillPlayAgain = false;
    }
    else {
        userWillPlayAgain = true;
    }
    return userWillPlayAgain;
}

// this method controls the entire game
public static boolean playGame(){

    boolean gameTerminate = false;
    int numOfUsers = howManyUsers();
    int [] randomNumbers = new int[numOfUsers];
    int [] numberOfGuesses = new int [numOfUsers];  
    int [][] numberBoard = new int [numOfUsers][100];

    // this for loop assigns the n random number(s) to the n player(s)
    for (int n = 0; n < numOfUsers; n++){
        randomNumbers[n] = generateRandomNumber(); 
        System.out.println("PLAYER " + (n+1) + "'s RANDOM NUMBER: " + randomNumbers[n]);
    }

    do { 
        for (int i = 0; i < numOfUsers; i++) {
            int guessedNumber = numberOfGuesses[i];

            if (guessedNumber == 0 || numberBoard[i][guessedNumber-1] != randomNumbers[i]) {
                System.out.println("Enter your guess Player " + (i+1) + ":");
                int enteredGuess = IO.readInt();


                numberBoard[i][guessedNumber] = enteredGuess;
                numberOfGuesses[i] = guessedNumber + 1;

                if(compareGuess(enteredGuess, randomNumbers[i])){
                    return true;

                }
            }
        } 

        /* int n = 0;
         * for ( int j = 0; j < numOfUsers; j++ ) {
            n = n + 1;
            System.out.println("Player " + n + " guessed " + numberOfGuesses[j]+ " time(s)"); }
         */


    } while (nextPlayer(numOfUsers, numberOfGuesses, randomNumbers, numberBoard) == false);


    // System.out.println("test"); 
    return gameTerminate;
}

public static void main(String[] args){
    boolean playing = true;
    while (playing) {
        playGame();

        System.out.println("Would you like to play again?");
        String answer = IO.readString();

        playing = playAgain(answer);
    }
    System.out.println("OK, goodbye!");
  }
}

Main issue as of right now: The game terminates and asks if user would like to play again after a player guesses their number, rather than after every player guesses their number. 截至目前的主要问题:游戏终止并询问用户是否要在玩家猜出自己的号码之后再次玩,而不是在每个玩家都猜出自己的号码之后再次玩。

Do I need actual Objects to make this happen and track every player or can this still be solved without objects? 我是否需要实际的对象来实现这一目标并跟踪每个玩家,还是可以在没有对象的情况下解决? This is a territory I am unfamiliar with. 这是我不熟悉的领域。

Right now your playGame method returns true back to main whenever any guess returns correct from compareGuess . 现在,无论何时从compareGuess返回正确的compareGuess您的playGame方法都将true返回给main

I would recommend setting up another array boolean[] correctGuess in playGame and mark the player number index as true if a player guesses correctly. 我建议在playGame设置另一个数组boolean[] correctGuess ,如果玩家猜true则将玩家编号索引标记为true You can use this new array to skip players who have guessed correctly, also. 您也可以使用这个新数组来跳过猜测正确的玩家。 Once all players are marked true you can return to main . 一旦所有玩家都标记为true,您就可以返回main

This won't help improve your current code, but the same game can easily implemented using objects. 这无助于改善您当前的代码,但是可以使用对象轻松实现同一游戏。 In my opinion, the code is cleaner and easier to read. 在我看来,该代码更加简洁易读。

Objects allow you to encapsulate the data required by each class. 对象使您可以封装每个类所需的数据。 The target, number of guesses, and whether they were correct is stored in the Person object instead of in a multi-dimensional array. 目标,猜测数目以及它们是否正确存储在Person对象中,而不是多维数组中。 The values can be accessed by referencing the Person object - eg person.numGuesses or person.target . 这些值可以通过参考被访问Person例如-对象person.numGuessesperson.target

By using objects, you can keep specific functionality scoped out of the main class. 通过使用对象,可以将特定功能的范围限制在主类之外。 ie abstract away the implementation. 即抽象出实现。 In a future version of the game, you may want to change the way the target value is incremented; 在游戏的未来版本中,您可能需要更改目标值的递增方式; by using objects, the change can be made in the class which sets and checks the value - without affecting any other classes. 通过使用对象,可以在设置和检查值的类中进行更改-而不会影响任何其他类。

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

public class Game {

    private final List<Person> personList = new ArrayList<>();

    private Game(int numPlayers) {

        for (int i = 0; i < numPlayers; i++) {
            personList.add(new Person(i)); // Fill the player list
        }

    }

    public static void main(String[] args) {

        System.out.print("Enter the number of players: ");

        Scanner sc = new Scanner(System.in);
        int numPlayers = sc.nextInt();

        // Initialise with the number of players
        Game g = new Game(numPlayers);
        g.mainLoop(); // Play the game

        boolean playAgain = false;

        do {

            System.out.print("Do you wish to play again?: ");
            String in = sc.next();

            playAgain = "yes".equals(in);

            if (playAgain) {
                g.resetAll();
                g.mainLoop();
            }

        } while (playAgain); // Only loop if they answered "yes"

    }

    private boolean allCorrect() {
        // Check if all players have answered correctly
        return personList.stream().allMatch(p -> p.correct);
    }

    private void resetAll() {
        for (Person p : personList) {
            p.reset(); // Reset each person
        }
    }

    private void mainLoop() {

        while (!allCorrect()) {
            for (Person p : personList) {
                p.doGuess(); // Ask for the guess
            }
        }

        // Everyone is correct, print the scores.

        for (Person p : personList) {
            System.out.println("Player " + p.id + " => " + p.numGuesses + " guesses");
        }

    }

}

class Person {

    final int id;
    int numGuesses;
    boolean correct;

    private int target;

    Person(int id) {
        this.id = id;
        target = new Random().nextInt(100); // Each player has a random target between 0-100
    }

    void doGuess() {

        if (correct) {
            // Skip turn if they're already correct
            return;
        }

        numGuesses++;

        System.out.print("Player " + id + " guess " + numGuesses + "(" + target + "): ");

        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt(); // Read the guess

        if (i == target) {
            correct = true;
            System.out.println("Correct!");
        }

    }

    void reset() {
        target = new Random().nextInt(100); // New target between 0-100
        numGuesses = 0; // Reset the counter
        correct = false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM