Guessing Game Ruby - ruby

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.

Related

How to get my number of attempts correct?

Hello all I previously asked how to fix a guessing number game on ruby which I got all done but now the number of attempts or tries is not reflecting nicely. Do I resolve this?
This is the code:
def check(int, r_int)
tries = 0
if int < r_int
tries +=1
puts "Guess Higher"
elsif int > r_int
tries +=1
puts "Guess Lower"
elsif int == r_int
win = true
puts "You are correct"
puts "You had attempted this "+ tries.to_s + " times to win"
abort
end
end
This is the main function:
def main
win = false
puts "Lets play a game!"
puts "I am thinking of a number between 1 and 100"
rnd_int = rand(100)
while not win
guess = gets.chomp.to_i
value = check(guess, rnd_int)
end
end
Overall everything works but the tries at the end of the game remains at 0 not sure where the mistake is.
Perhaps the code could look like following (just a suggestion)
def check(attempts,guess,number)
puts ">>> Attempts [#{attempts}]: guess higher" if guess < number
puts ">>> Attempts [#{attempts}]: guess lower" if guess > number
if guess == number
puts "Winner!!!"
return true
end
return false
end
if __FILE__ == $0
win = false
attempts = 5
puts "
Lets play a game!
I am thinking of a number between 1 and 100
"
number = rand(100)
while not win
print "Your guess: "
guess = gets.chomp.to_i
attempts -= 1
unless attempts
puts "You could not guess right"
exit
end
win = check(attempts, guess, number)
end
end
Output sample
Lets play a game!
I am thinking of a number between 1 and 100
Your guess: 50
>>> Attempts [4]: guess higher
Your guess: 80
>>> Attempts [3]: guess higher
Your guess: 90
>>> Attempts [2]: guess lower
Your guess: 86
Winner!!!
The code could be of following shape
win = false
attempts = 5
puts "
Lets play a game!
I am thinking of a number between 1 and 100
"
number = rand(100)
while not win
print "Your guess: "
guess = gets.chomp.to_i
attempts -= 1
score = guess <=> number
win = true if score == 0
puts "Attempts [#{attempts}]: guess higher" if score < 0
puts "Attempts [#{attempts}]: guess lower" if score > 0
unless attempts > 0
puts "You could not guess it right"
exit
end
end
puts "You are winner!!!"
Utilizing <=> operator the code would be shaped as following
attempts = 5
puts "
Lets play a game!
I am thinking of a number between 1 and 100
"
number = rand(100)
while true
print "Your guess: "
guess = gets.chomp.to_i
attempts -= 1
case guess <=> number
when 0
puts "\n>>> Nice guess, you are winner!!!"
exit
when -1
puts "Attempts [#{attempts}]: guess higher" if attempts > 0
when 1
puts "Attempts [#{attempts}]: guess lower" if attempts > 0
end
unless attempts > 0
puts "\n>>> Sorry, you could not guess it right"
exit
end
end

Ruby Guessing Game w 'Loop Do'

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.

gets.chomp three times in a row to exit

The task is taken from "Learn to Program" by Chrise Pine. The program is called 'Deaf Grandma'. Here's the task: "whatever you type, grandma (the program) should respond with this:
`HUH?! SPEAK UP, SONNY!`
unless you shout it (type in all capitals). In this case she responds with:
`NO, NOT SINCE 1938!`
Have Grandma shout a different year each time, maybe any year at random between 1930 and 1950. You have to shout BYE three times in a row. Make sure to test your program: if you shout
BYE three times but not in a row, you should still be talking to
Grandma."
Now, everything looks fine to me, except I didn't get where to put gets.chomp 3 times to exit a program. Eventually, I came up with this:
speak = gets.chomp
while speak != 'BYE'
puts 'HUH?! SPEAK UP, SONNY!'
if speak == speak.upcase
puts 'NO, NOT SINCE ' + (1930 + rand(20)).to_s + '!'
else repeat = gets.chomp
end
end
But in this case if I type BYE grandma still asks me:
`HUH?! SPEAK UP, SONNY!`
My question is: how can I properly make the program exit after I type BYE three times in a row?
Have a look at this, I've made some changes though. But should give you the expected output.
bye_count = 0
while true
speak = gets.chomp
if speak == 'BYE'
bye_count +=1
bye_count == 3 ? break : next
end
bye_count = 0 # Resets count
if speak == speak.upcase
puts 'NO, NOT SINCE ' + (1930 + rand(20)).to_s + '!'
else
puts 'HUH?! SPEAK UP, SONNY!'
end
end
You've not added anywhere in your code that using 'bye' 3 times will exit the program.
while bye < 3
Try looking at your code again and implementing the changes to exit after 3 byes.
Here's another way:
responses = ["", "", ""]
loop do
speak = gets.chomp
responses.shift
responses << speak
break if responses.all? { |r| r == "BYE" }
if speak == speak.upcase
puts 'NO, NOT SINCE ' + (1930 + rand(20)).to_s + '!'
else
puts 'HUH?! SPEAK UP, SONNY!'
end
end
Alternatively,
break if responses.uniq == ["BYE"]
puts "what can i do for your son?"
a=0
while a != 3
n= gets.chomp
if n.include? 'BYE'
puts "NO NOT SINCE #{rand(1897..1930)}".chomp
a = (a + 1)
end
if n != n.upcase
puts 'HUH?! SPEAK UP, SONNY!'.chomp
a=0
end
if n == n.upcase and n != 'BYE'
puts "NO NOT SINCE #{rand(1897..1930)}".chomp
a=0
end
end

Ruby script need fix

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.

Programming Ruby Slot Machine Game

I'm trying to make a slot machine game in Ruby and this is as far as I've gotten. It still won't run and says there is an error on the last line, which I do not know what is or how to fix it.
I need it to have an output similar to this:
How much total money would you like to play with today? 25
Total cash: $ 25
How much would you like to bet? 10
Cherry - Orange - Orange
You have won $ 20
Would you like to continue? (yes to continue) yes
Total cash: $ 35
How much would you like to bet?
etc…
I've already got the winnings set on there, like if you get two, you win twice your bet and if you get three, you win three times your bet.
But I get the error: 33: syntax error, unexpected $end, expecting kEND cash += cash + winnings
What is wrong with my code, and how do I fix it?
def multiplier(s1, s2, s3)
if s1 == s2 and s2 == s3:
multiplier = 3
elsif s1 == s2 or s2 == s3 or s1 == s3:
multiplier = 2
else
multiplier = 0;
return multiplier
def main()
slotImageList = ['Cherry', 'Orange', 'Plum', 'Bell', 'Melon', 'Bar']
cash = gets
puts "How much total money would you like to play with today? " +cash
while True:
puts("Total cash: $", cash)
bet = gets
puts "How much would you like to bet? " +bet
cash = (cash - bet)
slotImage1 = slotImageList.sample
slotImage2 = slotImageList.sample
slotImage3 = slotImageList.sample
puts "slotImage1", " - ", "slotImage2", " - ", "slotImage3"
winnings = bet * multiplier(slotImage1, slotImage2, slotImage3)
puts "You have won $" +winnings
cash = cash + winnings
cont = gets
puts "Would you like to continue? (yes to continue) " +cont
if cont != "yes":
puts "You have ended with $" +cash
else
puts " "
end
When you see the message:
unexpected $end, expecting kEND
you can translate it to, "I reached the end-of-file ("$end"), but I did not expect it, because I was still waiting to see an end statement." It means that you forgot to type at least one paired end, and you need to go through your code and ensure that it's indented properly so that you can visually match up the statements.
Below is the result of fixing your code to be correct.; in some spots you seemed to have used indentation to close a block (like Python) instead of the correct syntax.
def multiplier(s1, s2, s3)
if s1==s2 && s2==s3
3
elsif s1==s2 || s2==s3 || s1==s3
2
else
0
end
end
def run_slots!
slotImageList = %w[Cherry Orange Plum Bell Melon Bar]
print "How much total money would you like to play with today? "
cash = gets.chomp.to_i
loop do
puts "Total cash: $#{cash}"
print "How much would you like to bet? "
bet = gets.chomp.to_i
cash -= bet
slotImage1 = slotImageList.sample
slotImage2 = slotImageList.sample
slotImage3 = slotImageList.sample
puts "#{slotImage1} - #{slotImage2} - #{slotImage3}"
winnings = bet * multiplier(slotImage1, slotImage2, slotImage3)
puts "You have won $#{winnings}"
cash += winnings
print "Would you like to continue? (yes to continue) "
unless gets.chomp=="yes"
puts "You have ended with $#{cash}"
break
end
end
end
run_slots! if __FILE__==$0
If I were to take a few more liberties with it, here's how I might write it:
class SlotGame
SLOT_COUNT = 3
TOKENS = %w[Cherry Orange Plum Bell Melon Bar]
KEEP_PLAYING_RESPONSES = %w[y yes sure ok go]
def initialize(cash=nil)
unless cash
begin
print "How much total money would you like to play with today? "
cash = gets.to_i
puts "You must have a positive bank account to play!" if cash<=0
end until cash > 0
end
#cash = cash
end
def play_forever
begin
# Using begin/end ensures one turn will be played
# before asking the player if they want to go on
play_one_turn
end while #cash>0 && keep_playing?
puts "You have ended with $#{#cash}; goodbye!"
end
def play_one_turn
puts "Total cash: $#{#cash}"
begin
print "How much would you like to bet? "
bet = gets.to_i
puts "You only have $#{#cash}!" if bet > #cash
end until bet <= #cash
#cash -= bet
results = SLOT_COUNT.times.map{ TOKENS.sample }
puts results.join(' - ')
winnings = bet * multiplier(results)
if winnings>0
#cash += winnings
puts "You just won $#{winnings}!"
else
puts "Sorry, you're not a winner."
end
end
def keep_playing?
print "Would you like to continue? "
KEEP_PLAYING_RESPONSES.include?(gets.chomp.downcase)
end
private # Don't let anyone outside run our magic formula!
def multiplier(*tokens)
case tokens.flatten.uniq.length
when 1 then 3
when 2 then 2
else 0
end
end
end
SlotGame.new.play_forever if __FILE__==$0
Ok!!! I think I've figured it out from your code, #Phrogz!!!
To choose randomly from the array, like a slot machine would, I used slotImageList.shuffle.first, which shuffles the array, and takes the first element of the shuffled array.
def multiplier(s1, s2, s3)
if s1==s2 && s2==s3
3
elsif s1==s2 || s2==s3 || s1==s3
2
else
0
end
end
def run_slots!
slotImageList = %w["Cherry", "Orange", "Plum", "Bell", "Melon", "Bar"]
print "How much total money would you like to play with today? "
cash = gets.chomp.to_i
loop do
puts "Total cash: $#{cash}"
print "How much would you like to bet? "
bet = gets.chomp.to_i
cash -= bet
slotImage1 = slotImageList.shuffle.first
slotImage2 = slotImageList.shuffle.first
slotImage3 = slotImageList.shuffle.first
puts "#{slotImage1} - #{slotImage2} - #{slotImage3}"
winnings = bet * multiplier(slotImage1, slotImage2, slotImage3)
puts "You have won $#{winnings}"
cash += winnings
print "Would you like to continue? (yes to continue) "
unless gets.chomp=="yes"
puts "You have ended with $#{cash}"
break
end
end
end
run_slots! if __FILE__==$0
Thank you all soooo much!!! :D

Resources