Skip to content

Instantly share code, notes, and snippets.

@rodloboz
Created July 2, 2018 08:02
Show Gist options
  • Save rodloboz/f4a27c8fe13e6c648f05f7b2df4a8c6a to your computer and use it in GitHub Desktop.
Save rodloboz/f4a27c8fe13e6c648f05f7b2df4a8c6a to your computer and use it in GitHub Desktop.
Horse Race
# Player begins with 100$
# if player wins 50$
# otherwise loses 10$
# player = { wallet: 100 }
# list of a horses / race roster => Array
# ==== START LOOP ====
# display list of horses
# ask the user for the winning horse
# store user choice
# pick a random winner // run the race
# => sample (return a random item from Array)
# determine result
# print result (win or lost)
# determine if player has enough
# balance to continue
# ask user if they want to play again
# ===== END LOOP =====
require_relative 'race'
require_relative 'players'
require_relative 'welcome'
def display_horses(horses)
horses.each_with_index do |horse, index|
puts "#{index + 1} - #{horse}"
end
end
def print_results(choice, winner)
if choice == winner
puts "Congratulations! You won!"
else
puts "Sorry, you lost! The winner was #{winner}"
end
end
# interface
# Game starts
horses = [
"Jean",
"Shadowfax",
"Wyatt Earp",
"Bronco",
"Spirit",
"John Wayne"
]
welcome
player = create_player # hash
loop do
display_horses(horses)
display_balance(player[:wallet])
# user picks horse
horse_index = pick_horse(horses)
choice = horses[horse_index]
# determine winner
winner = pick_race_winner(horses)
if did_player_win?(winner, choice)
player[:wallet] = update_wallet(player[:wallet], 50)
else
player[:wallet] = update_wallet(player[:wallet], -10)
end
print_results(choice, winner)
if player[:wallet] < 10
puts "You have no more money! Game over!"
break
end
puts "Do you want to race again?"
print "> "
answer = gets.chomp
break if answer =~ /^n(o)?$/i
end
puts "Goodbye!"
# should return a player hash
def create_player
puts "Enter player name:"
print "> "
name = gets.chomp
# return value (hash):
{ name: name, wallet: 100}
end
# return horse index
def pick_horse(horses)
puts "Pick a horse (1-#{horses.size})"
print "> "
# return value:
gets.chomp.to_i - 1
end
def update_wallet(wallet, amount)
wallet + amount
end
def display_balance(wallet)
puts "You currently have $#{wallet}"
end
def pick_race_winner(horses)
# rand(0..horses.size)
horses.sample
end
def did_player_win?(winner, choice)
winner == choice
end
def welcome
puts "#################################"
puts "### ###"
puts "### H O R S E S ###"
puts "### ###"
puts "#################################"
puts "\n"
puts "Welcome to the racetrack!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment