HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

First text-based number-guessing game

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numbertextfirstgamebasedguessing

Problem

This was a learning experience. I have looked around and found some better ways to write some things but wanted a second opinion to look at what I've written and kind of analyze it as well.

I just finished my first "Text based game" sort of deal. I believe that it's poorly written and is pretty long for the short amount of game there is. I used a lot of unnecessary code such as pausing in between strings and such, although that's not what I'm asking.

I'm asking if you could find anything that can be done either more simply or more efficient.

The game goal is to basically guess a number and if you get it right, you win. As the levels progress the random numbers to guess and the ranges get higher, thus giving more points.

I tried to comment as much as I could for anyone to read. There are no errors with this game. It runs and works.

This is all 1 file. Here is a Pastebin to the code in case you want it.

```
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
//First text based game. Guess the random number that will be generated, and gather points!
public static void main(String[] args) {

try (Scanner store = new Scanner(System.in)){ //This < is used to create a new scanner variable . Used the try method because Eclipse was giving a 'resource leak'
Random rnd = new Random();

//Only 4 rounds so 4 random number ints.
int guess; //Will store the number that you will guess.
int totalpoints = 0;
char readytoplay;
int randomnumber1 = rnd.nextInt(1)+1; //First level of random numbers
int randomnumber2 = rnd.nextInt(2)+1;
int randomnumber3 = rnd.nextInt(4)+1;
int randomnumber4 = rnd.nextInt(9)+1;

System.out.println("Welcome to Guessing game!");
System.out.println("In this game, you will guess a number to see how lucky you are.");
System.out.println("As you progress, it gets harder and harder. ");
System.out.println("You will gain points as you go. ");
System.out.pr

Solution

I would try to split your code into multiple methods to make things easier to understand. Having everything in one huge main method is difficult to read and difficult to maintain, and generally considered a bad practice.

Having multiple methods also allows you to reuse blocks of code - one of the main principles of software development is "Don't repeat yourself."

Let's take a look at one of your main pieces of logic: checking their guess.

if (guess == randomnumber1)     {
        System.out.println("You were correct.");
        System.out.println("You guessed "+guess);
        System.out.println("The random number was "+randomnumber1);
        totalpoints = +1;                                       //This will add points to their total points. 
        System.out.println("You gained 1 point, Your total points are now: " +totalpoints);       //Obviously letting them know how many points they now have. 

        }
        else {
        System.out.println("You didn't guess correctly.");

        System.out.println("Your number:" +guess);
        System.out.println("The random number:" +randomnumber1);
        System.exit(0);     //Exiting the game, they did not have any points at the time so not displaying any points . 
        }


Side note: you should aim to indent each block of logic deeper than the level above it. Most editors will do this for you with a keyboard shortcut. E.g.

if (guess == randomnumber1) {
             System.out.println("You were correct.");
             ...


Anyway, looking at the above, the code checks the value, then if it is correct, prints a few lines and adds to your score, and if not, prints a few other lines. Compare this to the code in Round 2 (starting around line 138), and Round 3 (line 165), and Round 4 (195). Look familiar? They're practically identical. By refactoring these into one method and calling it several times, you gain several benefits:

  • your code will be more succinct and easier to read



  • if you have to update the code, you only have to update it once instead of four times



  • if you want to expand it to add a 5th, 6th, ...nth round, it will take much less time and effort.



Here's an example:

private int validateGuess(int currentScore, int pointsToAdd, int guess, int correctValue){
    if (guess == correctValue)     {
        System.out.println("You were correct.");
        System.out.println("You guessed "+guess);
        System.out.println("The random number was "+correctValue);
        int totalpoints = currentScore+pointsToAdd;    

        System.out.println("You gained "+pointsToAdd+" point(s), Your total points are now: " +totalpoints);       

    }
    else {
        System.out.println("You didn't guess correctly.");
        System.out.println("You guessed:" +guess);
        System.out.println("The random number was:" + correctValue);
        System.out.println("Game over. You ended with: " + currentScore + " point(s)");
        System.exit(0);    
    }
}


Now, you just need to call your method everywhere you had that code block before, e.g.

totalPoints = validateGuess(totalPoints, 1, guess, randomNumber1);
...
totalPoints = validateGuess(currentScore, 2, guess, randomNumber2);
...


Regarding all the Thread.sleep blocks, I would at least try to to compress them so they aren't so verbose:

try {
       Thread.sleep(900);
    }
    catch (InterruptedException ex)
    {  //Ignoring exception since this is just pauses console output      }


Some people would suggest even putting the try on one line, it all depends on style preference. Also note that in general, an empty exception block is a bad practice (you should either handle the exception or throw it), but at the minimum you should at least comment any situations where you aren't handling an exception (which I think is fine in this situation given the context of your program and the exception).

Lastly, just as you could refactor your common output code to a method, you can probably use a loop to minimize the repetition of your input code, making it easier to read and extend. It could be something as simple as:

int numRounds = 4;
for(int i=0, i<numRounds, i++){
   // Output your prompt for a guess
   // read in guess from input console
   // call validateGuess
}


Since the value range for the guess changes each round, you might need to add some logic for that.

Some other tips:

  • A common recommendation is to write the guess validation statement as (randomNumber1 == guess). That way if you accidentally remove an '=', you don't assign "guess" the value of "randomNumber". But what about the danger now of assigning "randomNumber" the value of "guess"? There's a solution for that:



  • Make your randomNumbers final. Then you won't risk accidentally changing their values: final int randomnumber1 = rnd.nextInt(1)+1;



That's all for now. Good luck!

Code Snippets

if (guess == randomnumber1)     {
        System.out.println("You were correct.");
        System.out.println("You guessed "+guess);
        System.out.println("The random number was "+randomnumber1);
        totalpoints = +1;                                       //This will add points to their total points. 
        System.out.println("You gained 1 point, Your total points are now: " +totalpoints);       //Obviously letting them know how many points they now have. 

        }
        else {
        System.out.println("You didn't guess correctly.");

        System.out.println("Your number:" +guess);
        System.out.println("The random number:" +randomnumber1);
        System.exit(0);     //Exiting the game, they did not have any points at the time so not displaying any points . 
        }
if (guess == randomnumber1) {
             System.out.println("You were correct.");
             ...
private int validateGuess(int currentScore, int pointsToAdd, int guess, int correctValue){
    if (guess == correctValue)     {
        System.out.println("You were correct.");
        System.out.println("You guessed "+guess);
        System.out.println("The random number was "+correctValue);
        int totalpoints = currentScore+pointsToAdd;    

        System.out.println("You gained "+pointsToAdd+" point(s), Your total points are now: " +totalpoints);       

    }
    else {
        System.out.println("You didn't guess correctly.");
        System.out.println("You guessed:" +guess);
        System.out.println("The random number was:" + correctValue);
        System.out.println("Game over. You ended with: " + currentScore + " point(s)");
        System.exit(0);    
    }
}
totalPoints = validateGuess(totalPoints, 1, guess, randomNumber1);
...
totalPoints = validateGuess(currentScore, 2, guess, randomNumber2);
...
try {
       Thread.sleep(900);
    }
    catch (InterruptedException ex)
    {  //Ignoring exception since this is just pauses console output      }

Context

StackExchange Code Review Q#117631, answer score: 7

Revisions (0)

No revisions yet.