Programming Ruby Slot Machine Game - ruby

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

Related

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

Using `while` to repeat the process if user wants to do another operation

I wrote the following code:
puts "Money to deposit:"
money_invested = gets.to_f
puts "Time in days:"
time_investment = gets.to_f
puts "Indicate interest rate:"
interest_rate = gets.to_f
investment_calculation =
money_invested * (1 + interest_rate / 100 * time_investment / 365)
puts "Your money will be: $%.2f." % investment_calculation
I want to ask if the user wants to perform another operation:
puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
another.operation = gets.chomp
If the user says N, I would say something like puts "Thanks for your time! The app will be closed in one minute. But if the user wants to run another operation (type Y), I need to run all the code again. I know this can be done with while, but don't know exactly. Any ideas?
You can maintain an infinite loop, and break it when desired:
NO = %w{ n no nope negative negatory nyet }
loop do
# all of your various questions & responses
puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
response = gets.chomp
break if NO.include?(response.downcase)
# Additional code could go here, if it's appropriate
# to perform repeated actions after user indicates
# they don't want to quit
end
# cleanup code here
Use a boolean variable to switch between true/false based on user input. The first run it will be implicitly true:
do_loop = true
while do_loop
puts "Money to deposit:"
money_invested = gets.to_f
puts "Time in days:"
time_investment = gets.to_f
puts "Indicate interest rate:"
interest_rate = gets.to_f
investment_calculation = money_invested * (1 + interest_rate/100 * time_investment/365)
puts "Your money will be: $%.2f." % investment_calculation
puts "Would you like to perform another operation? Indicate 'Y' or 'N'"
answer = gets.chomp
# assign "true" to loop variable only if first character is 'Y' or 'y'
do_loop = answer.size > 0 && answer.downcase[0] == 'y'
end

Program won't output what it's supposed to

I am following tutorial and I can't figure out what I am doing wrong. It's outputting everything up to if down
puts "we are going down the cave" I can't get it to output the else statement or anything afterwards. I am just learning and the answer is probably really simple.
puts("Would you like to go up or down?")
user_input = gets()
down = "cave"
up = "mountain"
if down
puts "we are going down the cave"
else up
puts "we are going up the mountain"
puts("Pick a number between 1 and 100")
LOCATION = "cave"
NUMBER = gets()
if NUMBER == 100
puts "You've achieved enlightment in the #{LOCATION}! Spread joy around the world!"
elsif NUMBER >= 50 > 100
puts "There are #{NUMBER} goblins in the #{LOCATION}. WE MUST FIGHT!"
elsif NUMBER > 20 > 50
puts "There is still hope that we will make it to the #{LOCATION}. before the #{NUMBER} Snufflebums get us!"
else NUMBER <= 20
puts "We have conquered the Goon Squad of the #{LOCATION}.. It only took us #{NUMBER} years!!!"
end
end
down is "cave" and is always 'truthy' so if down is always, always true. You want to be testing the user_input, not the variable down
What I think you want is...
user_input = gets.chomp
# you need the chomp to remove the return character
down = "cave"
up = "mountain"
if user_input == down
puts "we are going down the cave"
elsif user_input == up
puts "we are going up the mountain"
end
# you need the end statement, otherwise everything that follows is part of the "else"
And remove the last 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.

Guessing Game 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.

Resources