I'm trying to write a simple high-low program that will output like this:
$ ./highlow.rb
Please tell me the max value of the random number: 100
Ok. The random number is generated between 1 and 100.
Make your guess: 50
That's too low. Guess again: 75
That's too high. Guess again: 63
That's too low. Guess again: 68
Correct! You guessed the answer in 4 tries!
Would you like to play again? no
OK. Goodbye.
$
This is the code I have, but I'm going wrong somewhere. It appears to work sometimes:
count=0
play = true
while play = true
print "Please tell me the max value of the random number: "
max= gets.to_i
num= rand(max)
puts "Ok. The random number is generated between 1 and " + max.to_s +
"."
print "Make your guess: "
guess=gets.to_i
while guess != num && play != false
if guess > num
print "That's too high. Guess again: "
guess=gets.to_i
count+=1
end
if guess < num
print "That's too low. Guess again: "
guess=gets.to_i
count+=1
else
break
end
end
puts "Correct! You guessed the answer in " + count.to_s + " tries!"
print "Would you like to play again? "
answer=gets.chomp!
if answer == 'n'
play = false
break
end
if
answer == 'y'
play = true
end
end
puts "OK. Goodbye"
Any suggestions? Where am I going wrong?
I think your problem (the one I can see anyway) is with number checking code.
If guess is greater than num, then the first if statement will execute, but then the second one will redirect to the else, breaking out of the loop.
You need to use an elsif. Try changing it to this:
if guess > num
print "That's too high. Guess again: "
guess=gets.to_i
count+=1
elsif guess < num
print "That's too low. Guess again: "
guess=gets.to_i
count+=1
else
break
end
Related
I created a guessing game through Ruby and I believe the structure of my code is off. When entering 'Cheat', you are given the random number then asked to type it in again. When typed in again, it says the random number is not correct and always defaults to my 'elseif' in line 45.
puts "Hey! I'm Sam. What's your name?"
name = gets
puts "Welcome #{name}. Thanks for playing the guessing game.
I've chosen a number between 1-100.
You'll have 10 tries to guess the correct number.
You'll also recieve a hint when you're guess is wrong.
If you feel like being a big ol cheater, type 'Cheat'.
Let's get started..."
random_number = rand(1...100)
Cheat = random_number
counter = 10
loop do
break if counter == 0
divisor = rand(2...10)
guess = gets.chomp
break if guess.to_i == random_number
counter -= 1
if
guess == random_number
puts 'You guessed the right number! You win!'
end
if counter < 4
puts "You can go ahead and cheat by typing 'Cheat'..."
end
if guess.to_s.downcase.eql? "cheat"
puts "The random number is #{random_number} you CHEATER!! Go ahead and type it in..."
guess = gets.chomp
puts = "You win cheater!"
end
if
guess.to_i < random_number
puts 'Ah shucks, guess again!'
guess = gets.chomp
elsif
guess.to_i > random_number
puts 'Too high, guess again!'
guess = gets.chomp
end
if random_number % divisor == 0
puts "Thats not it.\n #{guess} is #{guess.to_i > random_number ? 'less' : 'greater'} than the random number.
The random number is divisible by #{divisor}.\nTry again: "
elsif
puts "That's not the random number.\n #{guess} is #{guess.to_i > random_number ? 'less' : 'greater'} than the random number.
The random number is NOT divisible by #{divisor}.\nTry again: "
end
end
if counter > 0
puts "The number is #{random_number}! You win!"
else
puts "You lose! Better luck another time."
end
this is the response i get in the terminal
Let's get started...
Cheat
The random number is 96 you CHEATER!! Go ahead and type it in...
96
Thats not it.
96 is greater than the random number.
The random number is divisible by 8.
Try again:
The problem is here:
puts = "You win cheater!"
You're assigning the string "You win cheater!" to a local variable named puts. Changing it to this fixes the problem:
puts "You win cheater!"
You'll probably also want to put a break after that line.
As an aside, this pattern:
loop do
break if counter == 0
# ...
end
...would be better expressed as:
while counter > 0
# ...
end
...or:
until counter == 0
# ...
end
Also, you should always put the condition for an if/elsif/whathaveyou on the same line as if et al. Why? Because if you don't you get bugs like this:
if random_number % divisor == 0
# ...
elsif
puts "..."
end
Can you spot the bug? You forgot to put a condition after elsif, or used elsif when you meant to use else, which means that the return value of puts (which is always nil) is being used as the condition, just as if you had written elsif puts "...".
If you make a habit of always putting the condition on the same line as if/elsif, your eye will get used to it and errors like this will jump out at you.
To calculate $totalNoOfGuesses you would add $noOfGuesses together from each game played, correct? How do I execute that in my code? I've tried several different options, but it doesn't work. Am I supposed to be creating an array or something?
def play_game
$noOfGuesses=0
$gameCount+=1
number = generate_number
loop do
print "\nEnter your guess and press the Enter key: "
reply = STDIN.gets
reply.chop!
reply = reply.to_i
$noOfGuesses+=1
Between this would be if reply > or <, too high or too low... reply = get.to_i
$noOfGuesses=0
$gameCount=0
$totalNoOfGuesses=0
$avgNoOfGuesses=0
answer = ""
loop do
Console_Screen.cls
print "Are you ready to play the Ruby Number Guessing Game? (y/n): "
answer = STDIN.gets
answer.chop!
break if answer == "y" || answer == "n"
end
if answer == "n"
Console_Screen.cls
puts "Okay, perhaps another time.\n\n"
else
loop do
SQ.play_game
Console_Screen.cls
print "It took you #{$noOfGuesses} attempt#{'s' if $noOfGuesses > 1}.\n"
print "You have played #{$gameCount} time#{'s' if $gameCount > 1}.\n"
print "It has taken you #{$totalNoOfGuesses} attempts in #{$gameCount} game#{'s' if $gameCount >1}.\n\n"
I'm having a problem with my ruby script. If anyone could help, I'd really appreciate it. The problem is that the number is stuck between 1-2; where 2 is too high and 1 is too low. The guesses should be integers only.
#!/usr/bin/ruby
def highLow(max)
again = "yes"
while again == "yes"
puts "Welcome to the High Low game"
playGame(max)
print "Would you like to play again? (yes/no): "
again = STDIN.gets.chomp
if again == 'no'
puts "Have a nice day, Goodbye"
end
end
end
#This method contains the logic for a single game and call the feedback method.
def playGame(max)
puts "The game gets played now"
puts "I am thinking of a number between 1 and #{max}." #It show what chosen by user
randomNumber = rand(max)+ 1
print "Make your guess: "
guess = STDIN.gets.chomp
feedback(guess, randomNumber)
end
#Start while loop
#Logic for feedback method. It's ganna check the guess if it's high or low.
def feedback(guess, randomNumber)
count = 1
while guess.to_i != randomNumber
count = count + 1
if guess.to_i < randomNumber
print "That's too low. Guess again: "
else
print "That's too high. Guess again: "
end
guess = STDIN.gets.chomp
end
puts "Correct! You guessed the answer in #{count} tries!"
end
highLow(ARGV[0])
Change your last line to this:
highLow(ARGV[0].to_i)
The ARGV array contains all the passed in arguments as strings, so you have to cast it to integer.
So i have been learning ruby as of late and i am working on this code for practice purposes but i cannot seems to be able to solve this problem any help would be appreciate it.
This is are the guidelines i am following:
clear the screen
greet the player
explain the rules of the game to the player
generate a random number between 0 and x (x being a variable that can be set to any integer)
allow the player n number of guesses (n being a variable)
keep track of the guess history
don't count repeated guesses against the player
congratulate the player when he/she guesses correctly
alert the player when there is only one guess remaining
print the guess history at the end of the game
count number of games won IN A ROW
count number of games won in total
congratulate the play on 3 games won IN A ROW
ask if the player wants to play again
thank the player for playing games if the number of games played is greater than 2
please keep in my that this is work in progress and i have not completed all the guideline, however my questions is with one particular part of it.
here is the code:
guess = Array.new
puts guess.class
def ask()
puts "Please answer in a 'y' or 'n' only!"
puts "Would like to play again?"
end
def guess_check_against()
g = guess.last
unless guess.include?(g) != guess
count+=1
else
puts "sorry you have guessed that number before, Guess Again: "
guess << gets.to_i
count+=1
end
end
puts "what is your name?"
user= gets.chomp
puts "Hello #{user}!!"
max_user_attempts = 4
#attempt_counter = 0
directions = "\nLets play a guessing game! You have
#{max_user_attempts.to_s} guesses before you lose."
print directions
g = guess.last
win = 0
count = 0
play = true
while play == true
puts "Please tell me the max value of the random number: "
max= gets.to_i
num= rand(max)
puts "Ok. The random number is generated between 1 and " + max.to_s + "."
puts "Make your guess: "
guess << gets.to_i
guess_check_against()
#attempt_counter+=1
while guess != num && play != false
if g > num && #attempt_counter < max_user_attempts
print "That's too high. Guess again: "
guess << gets.to_i
guess_check_against()
#attempt_counter+=1
elsif g < num && #attempt_counter < max_user_attempts
print "That's too low. Guess again: "
guess << gets.to_i
guess_check_against()
count+=1
#attempt_counter+=1
else
break
end
end
if #attempts_counter >= max_user_attemtps
puts "Sorry! you lost! Try Again"
break
else #attempts_counter <= max_user_attempts
puts "Correct! You guessed the answer in " + count.to_s + " tries!"
win+=1
end
if win >= 3
puts "Congratulation! you have #{win} number of games in a row"
ask()
answer = gets.chomp!
elsif win < 3
ask()
answer = gets.chomp!
else
break
end
if answer == 'n'
play = false
break
end
if answer == 'y'
play = true
count = 0
end
end
puts "Ok. Goodbye!!"
and here is the error i keep receiving when i try to run this program:
guessing_game.rb:12:in `guess_check_against': undefined local variable or method `guess' for main:Object (NameError)
from guessing_game.rb:45:in `<main>'
when i try to use irb to run the same scenario it works completely fine.
i can not figure out what i am doing wrong, please help!!
The method definition
def guess_check_against()
g = guess.last
...
end
has its own scope, and the local variable
guess = Array.new
that you defined outside of it, is not accessible inside the method definition. guess is not defined inside the method definition. You can change the code so that the method takes that as an argument, and it will become accessible.
I have been trying to figure out how to make it so that the user can only enter a positive whole number between 1 and 100 for this simple High/Low guess game. I would like it so anything other then a whole number between 1 and 100 will inform the user they can't do that for all inputs. Is there a simple way to do this?
What I have now:
count=0
play = true
while play == true
print "Give me a random number between 1 and 100: "
max= gets.to_i
num= rand(max)
puts "Now guess between 1 and " + max.to_s +
"."
print "What is your guess?: "
guess=gets.to_i
while guess != num && play != false
if guess > num
print "Too high! "
guess=gets.to_i
count+=1
elsif guess < num
print "Too low! "
guess=gets.to_i
count+=1
else
break
end
end
puts "Good Job! You figured it out in " + count.to_s + " attempts!"
print "Want to try again? y/n "
answer=gets.chomp!
if answer == 'n'
play = false
break
end
if
answer == 'y'
play = true
end
end
puts "Maybe next time..."
The easiest way to do that is to use a regular expression and a range.
guess = gets.chomp
if(guess =~ /\A\d+\Z/ && (1..100) === guess.to_i)
#do stuff
else
puts "Please enter a valid number"
end
The regular expression ensures that we get an input composed only of digits (a whole number) and the ranged checks to see if it is between 1 and 100.
if (1..100).include?(guess) && 0 == guess % 1
# ...
end