Ask your own question, for FREE!
Computer Science 18 Online
OpenStudy (anonymous):

1. Modify the program so that there is a limit on the number of guesses (for example: maximum of 10 guesses). If the user guesses the correct number before their attempts run out they win, otherwise the computer wins. There are better and worse ways to do this, and your effort will be graded accordingly. 2. Modify the program so that the computer keeps track of how long it takes the user to play the game and gives more points if the user is able to guess the number quickly. This feature may require you to do additional research into the programming language.

OpenStudy (anonymous):

So I have a program working already and above is what I need to add. The game still has to be able to play the previous 2 levels though, and add modifications for level 3.

OpenStudy (anonymous):

I would need to see what you have already, but it sounds like something as simple as a try = 1 while try<11: if conditions are met: print 'you win' else: try = try +1 if try = 11: print 'computer wins'

OpenStudy (anonymous):

Here is what I have so far for level 2 + 3 public class LevelThree { public static void main (String [] args){ System.out.println("Welcome to the Random guessing game, please enter the minimum value of the number range you want the computer to generate."); int minNumber = In.getInt(); System.out.println("Please enter the maximum value of the number range you want the computer to generate."); int maxNumber = In.getInt(); int randomNumber = (int) (Math.random()* (maxNumber-minNumber)) + (minNumber); int userValue; do { System.out.println("Enter a number in the range of: " + minNumber + " to " + maxNumber); userValue = In.getInt(); if (userValue > randomNumber && userValue <= maxNumber) { System.out.println("Your guess is too high."); } else if (userValue < randomNumber && userValue >= minNumber) { System.out.println("Your guess is too low."); } else if (userValue >maxNumber || userValue < minNumber) { System.out.println("Invalid guess, guess a number within the specified range."); } } while (randomNumber != userValue); System.out.println("Congratulations! You guessed the number correctly!"); } }

OpenStudy (woodrow73):

oi sciencewiz @sciencewiz3000

OpenStudy (anonymous):

Hi @woodrow73

OpenStudy (anonymous):

do you how to set up a program so that you have the option of playing levels?

OpenStudy (woodrow73):

yes- basically have the user input what level they want to play (1 - x), then only execute the block of statements under the 1, then you can loop it around as many times to the beginning as you want. To do this.. you can have a switch statement, or if else if. which do you prefer?

OpenStudy (woodrow73):

or want to learn

OpenStudy (woodrow73):

@sciencewiz3000

OpenStudy (anonymous):

I'm going to try a switch statement.

OpenStudy (woodrow73):

ok, you got this. After the user completes the 'level' you can even ask if the user wants to try another level or not, in a do while loop that surrounds almost everything

OpenStudy (woodrow73):

speaking of levels.. I'm making my first text-based game right now. It's surely one of a kind lol.

OpenStudy (anonymous):

lol, yeah and do you know how I can time the game, give extra points for a faster time, and have an option for the computer to play against itself?

OpenStudy (woodrow73):

Ya, there is some syntax to time the length of a program, or between 2 points of it (returns it in milliseconds) I have yet to learn it myself but I'll dig it up a self-playing computer? :p It sounds like fun, though the algorithm wouldn't be simple.

OpenStudy (woodrow73):

``` long startTime = System.currentTimeMillis(); for(stuff) { //do code } long endTime = System.currentTimeMillis(); long programLength = endTime - startTime; double programLengthSec = programLength/1000; //convert to seconds if(programLengthSec < 20) //user gets tons of points else if(programLengthSec < 40) //user gets some points else //user gets few points ```

OpenStudy (anonymous):

Thx :0

OpenStudy (anonymous):

:)

OpenStudy (woodrow73):

Hello. I made a computer that plays itself at the random number game :p

OpenStudy (woodrow73):

I have to admit, it's very efficient at getting the answer.. it approaches it mathematically, except for the fact that it's starting number is random, not 50.

OpenStudy (woodrow73):

Wanna know the logic behind it?

OpenStudy (anonymous):

Yes please!

OpenStudy (lyrae):

I'm guessing you used the having method (binary search) ? If you did, you have to start at 100/2 = 50 to reach optimal performance! From that algoritm one can also deduct that it's aways possible to win if you have \[\lceil \log_2(N)\rceil \]guesses. So if we have the range 1-100\[\lceil \log_2(100) \rceil = \lceil 6.64385618977 \rceil = 7\]it's always possible to win in 7 guesses. A good scoring-system should take this into account!

OpenStudy (lyrae):

halving method*

OpenStudy (anonymous):

@Lyrae so I want this program to give the user the option of playing different levels, however with this code, the program plays each level and then moves onto the next one when the number is guessed correctly. Do you know how to fix this so that it just plays the one level that the user chooses? public class LevelFour { public static void main (String [] args){ System.out.println("Welcome to the Random Number Guessing Game. Please enter which level you want to play, 1, 2, or 3."); int Level = In.getInt(); if (Level == 1) System.out.println("Welcome to level 1."); int randomNumber = (int) (Math.random()*100 + 1); int userValue; System.out.println("Welcome to the Random guessing game. Enter a number between 1 and 100."); do { System.out.println("Enter a number in the range of 1 to 100."); userValue = In.getInt(); if (userValue > randomNumber && userValue <= 100) { System.out.println("Your guess is too high."); } else if (userValue < randomNumber && userValue >=1) { System.out.println("Your guess is too low."); } else if (userValue >100 || userValue < 1) { System.out.println("Invalid guess, guess a number in the range 1 - 100."); } } while (randomNumber != userValue); System.out.println("Congratulations! You guessed the number correctly!"); if (Level ==2) System.out.println("Welcome to level 2."); { System.out.println("Welcome to the Random guessing game, please enter the minimum value of the number range you want the computer to generate."); int minNumber = In.getInt(); System.out.println("Please enter the maximum value of the number range you want the computer to generate."); int maxNumber = In.getInt(); randomNumber = (int) (Math.random()* (maxNumber-minNumber)) + (minNumber); do { System.out.println("Enter a number in the range of: " + minNumber + " to " + maxNumber); userValue = In.getInt(); if (userValue > randomNumber && userValue <= maxNumber) { System.out.println("Your guess is too high."); } else if (userValue < randomNumber && userValue >= minNumber) { System.out.println("Your guess is too low."); } else if (userValue >maxNumber || userValue < minNumber) { System.out.println("Invalid guess, guess a number within the specified range."); } } while (randomNumber != userValue); System.out.println("Congratulations! You guessed the number correctly!"); } if (Level == 3) System.out.println("Welcome to level three of the game."); } }

OpenStudy (lyrae):

You need to put all the game logic into another while-loop. So the player get to choose a new level when the game restarts. You also have to practcie your block statements. This ``` if (someThing == 1) doSomeThing(); doSomethingElse(); ``` and this ``` if (someThing == 1) doSomeThing(); { doSomethingElse(); } ``` are the same things! And NOT the same as ``` if (someThing == 1) { doSomeThing(); doSomethingElse(); } ``` Read your code again and see if you can find what i mean.

OpenStudy (woodrow73):

In making the self-playing computer, I used a halving method, yes. There is a floor variable, which starts out at 1, and a ceilling variable which starts out at 100. The computer's first guess is random, (I know starting it's guess at 50 will always yield the fastest results, but I find it more interesting if it starts randomly), and if it's guess is too high, then the ceilling variable becomes equal to the computer's guess, and then the computer guesses halfway between it's latest guess and the floor variable (1), and if the guess is too low, the low variable updates to the computer's guess, next the computer will guess halfway between it's latest guess and the ceilling variable, this process repeats until it hits the sweet spot. For aesthetics, I print all of the computer's output (including each guess & whether it was too high or low, until it gets the right answer) onto a .txt file with the PrintWriter class, then afterwards, I read off line by line (using File & Scanner classes) with a .4 second delay to simulate the computer guessing like a human would (using Thread.sleep(400); inside a try/catch block)

OpenStudy (anonymous):

@woodrow73 Can you tell what I did wrong in the code that I posted above or what I need to do to make the levels run separately as level 1, 2, and 3?

OpenStudy (anonymous):

when I did switch statements I also got errors.

OpenStudy (woodrow73):

when the user inputs a number into variable 'int level', one of the 3 if statements will execute depending on which number you enter. Though just as lyrae said above, you are missing the brackets for the if statements.. so without the brackets, the ONLY thing that executes if the if statement is true, is the 1 line underneath it.. To attach multiple lines to an if statement, use brackets in the bollowing manner: if(level == 1) { //starting bracket is right after the ending parenthese //statements //statements //statements //statements that are done only if level == 1 } //ending bracket So everything in the brackets there will execute ONLY if level == 1. In your code, you simply have the brackets jumbled in the improper format.. relatively easy fix :p

OpenStudy (anonymous):

Oh ok thanks, now I understand what lyrae was trying to say :P thanks, I will try that right now.

OpenStudy (anonymous):

Awesome! It is working with the levels now! Now I am going to try the code for timing the game.

OpenStudy (woodrow73):

nice! Thread.sleep(enter milliseconds here 1000ms = 1 sec); inside a try/catch block like try{ Thread.sleep(enter ms here); }catch(Exception e){ }

OpenStudy (anonymous):

@Lyrae in order to limit the number of guesses to 10 for instance, would I need to use a for loop, if so, how do I make it so that if the correct number is guessed, the loop exits but if the incorrect number is entered it goes up to 10 guesses before the final print statement?

OpenStudy (woodrow73):

Hello

OpenStudy (anonymous):

hey

OpenStudy (woodrow73):

show me how you would make a for loop so that it would stop after 10 'loops' (the terminology for this is 'iterations')

OpenStudy (anonymous):

for (int Guess = 0; Guess < 10; Guess++)

OpenStudy (woodrow73):

nice, now all you need is to add on to the logical operator.. imagine the boolean expression as the same as it would be in an if statement

OpenStudy (woodrow73):

by changing the boolean expression of the for loop to include a boolean variable that turns true once the person guesses the right number-- how would you do that?

OpenStudy (anonymous):

so like: userValue == randomValue?

OpenStudy (anonymous):

so wait, how would you put that kind of statement into the for loop?

OpenStudy (woodrow73):

that's a valid statement. In a for loop header, it itself is composed of 3 components: A: initializer, B: the boolean expression, C: the update expression. It is possible to have multiples of all of these components - when using multiple initializers, you separate them by commas.. when using multiple update expressions you separate them by commas: like so: note: you only need to say the data type once (int), as I did below, it will declare count and up as new int variables. ``` for(int i = 0, count = 0, up = 0; count < 10; count++, i--) ``` As you can see, the initializers and update expressions are separated by commas, though in order to have multiple boolean expressions- we must rely upon logical operators.. those being && != == || ect.. so: ``` for(int i = 0; i < 10 && !boolVar; i++) ``` so in the for loop above, it will iterate until either i reaches a value of 10, or boolVar becomes true. Notice the boolVar has the ! before it.. this means that it is logically inverted.. so as long as boolVar remains false, !boolVar will result as true. You can be as creative with the boolean expression as you please-- And to add on about for loops, note that the semi-colon ; is always used twice in a for loop, once to signify the end of the initializer, and a 2nd time to signify the end of the boolean expression (note ; is not used after the update expression) however you do not necessarily always need an initializer, or even an update expression, but you do always need the semi-colons ; that symbolize the end of the initializer and boolean expression; for example- these have proper syntax: ``` int i = 1; for(; i<100;) { i = i + i; } ``` or even ``` for(int i = 0; i < 50;) { i++; } ```

OpenStudy (woodrow73):

``` for(int i = 0; i < 10 && !boolVar; i++) ``` I'll touch upon the logic of that boolean expression again - so when using &&, it signifies that both the left side of the &&, as well as the right side must BOTH be true in order for the statement to be true... as long as the statement is true, the for loop will continue to iterate (aka: loop), so the moment i reaches 10 OR boolVar gets set = to true, the statement will become false, and the for loop will stop iterating(looping).

OpenStudy (woodrow73):

so pretty much any logical expression you can imagine can be expressed this way.. with practice it becomes easy to make thought into code like that :p.

OpenStudy (anonymous):

@Lyrae do you think you could look over what I have for this porgram. I want to make the loop execute 10 times, but only if the user enters an incorrect value, and I want the time to be printed only at the end of the game. I took woodrow73's suggestions but I think I may be missing something.

OpenStudy (anonymous):

else if (Level == 3){ System.out.println("Welcome to level 3.You will have only 1 guess to get guess a random number between a range that you will set."); { System.out.println("Welcome to the Random guessing game, please enter the minimum value of the number range you want the computer to generate."); int minNumber = In.getInt(); System.out.println("Please enter the maximum value of the number range you want the computer to generate."); int maxNumber = In.getInt(); if (minNumber > maxNumber) { System.out.println("The max value cannot be less than the min

OpenStudy (anonymous):

System.out.println("Welcome to the Random guessing game, please enter the minimum value of the number range you want the computer to generate."); int minNumber = In.getInt(); System.out.println("Please enter the maximum value of the number range you want the computer to generate."); int maxNumber = In.getInt(); if (minNumber > maxNumber) { System.out.println("The max value cannot be less than the min value. Please try again and enter a valid min number."); minNumber = In.getInt(); System.out.println("Please enter a valid max number."); maxNumber = In.getInt(); } int randomNumber = (int) (Math.random()* (maxNumber-minNumber)) + (minNumber); int userValue; int attempts = 0; long startTime = System.currentTimeMillis(); for (attempts = 0; attempts < 1; attempts++) { System.out.println("Enter a number in the range of: " + minNumber + " to " + maxNumber); userValue = In.getInt(); if (userValue > randomNumber && userValue <= maxNumber) { System.out.println("Your guess is too high. Sorry, your guesses have run out. The computer wins."); } else if (userValue < randomNumber && userValue >= minNumber) { System.out.println("Your guess is too low. Sorry, your guesses have run out. The computer wins."); } else if (userValue >maxNumber || userValue < minNumber) { System.out.println("Invalid guess, guess a number within the specified range."); } else if (userValue == randomNumber) { System.out.println("Congratulations! You guessed the number correctly!You have won the game!"); } long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println("Your total time is: " + totalTime + "Milliseconds."); if (totalTime > 0 && totalTime < 2000 && userValue == randomNumber) { System.out.println("Excellent, you've won with 100 points!"); } else if (totalTime > 2000 && totalTime < 8000 && userValue == randomNumber) { System.out.println("Good, you've won with 50 points."); } else if (totalTime > 8000 && totalTime < 1000 && userValue == randomNumber) { System.out.println("Satisfactory, you've won with 10 points."); } else { System.out.println("Good try, you've won, but you have not earned any additional points."); } } }}}}

OpenStudy (woodrow73):

``` else if (totalTime > 8000 && totalTime < 1000 && userValue == randomNumber) { System.out.println("Satisfactory, you've won with 10 points."); } ``` quick bug fix- totalTime will never be greater than 8 seconds and less than 1 second- I think you mean totalTime < 10000 instead of 1000.

OpenStudy (anonymous):

oh yeah oops

OpenStudy (woodrow73):

``` boolean correctGuess = false; for(int i = 0; i < 10 && !correctGuess; i++) { System.out.println("guess a secret value between 20 and 50, u have 10 guesses"); int input = ln.getInt(); if(input == 44) correctGuess = true; } if(correctGuess) System.out.println("Congrats on the correct guess"); else System.out.println("You didn't guess the secret value within 10 guesses"); ```

OpenStudy (anonymous):

Ohhh ok, so that's what I was missing there!

OpenStudy (woodrow73):

The code I just posted will iterate between 1 and 10 times inclusive.. because if the user inputs the correct value, the boolean expression will be false.. if you have any questions about it, lemme know.

OpenStudy (anonymous):

Thanks! So then, for when it prints out the time, will the time then print after the loop not changing what I had before or would I have to adjust that too so that the time is not printed after every guess and so that if the person loses the time and "good you win" is not printed?

OpenStudy (woodrow73):

how the milliseconds is oriented is fine, even if you do multiple loops, because the endTime should update every iteration to the correct value- also, the "good you win" will print when you guess it wrong- for cleanliness sake, you can put the entire if else if else inside a giant if statement that only executes if userValue = random number. At that point you can even take out the userValue = random number inside of the nested if else statements, because that will already be decided in the initial if statement.. like ``` if(user value == random number) { //test the milliseconds for extra points } else System.out.println("You guessed wrong"); ``` and that way you can even add an else statement that executes when you guess wrongly.

OpenStudy (anonymous):

oh ok, so i will just add that in the loop or outside?

OpenStudy (woodrow73):

you're going to make the for loop iterate more than 1 time?

OpenStudy (woodrow73):

ya it's fine to put it inside the for loop- if the for loop has multiple iterations, make sure that the loop stops once the user guesses the correct number, and if it's only one iteration- then it's fine to put it inside or outside the for loop.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!