Created
February 6, 2014 18:48
-
-
Save mjyoung/8850241 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pry' | |
class RaceTrack | |
attr_accessor :time, :cars | |
def initialize | |
@time = 0 | |
@cars = [] | |
end | |
def add_racecar(racecar) | |
@cars << racecar | |
end | |
def setup_race | |
puts "Welcome to the Race!" | |
puts "***--------------***" | |
while true | |
puts "Please input a driver name, OR leave empty and press [ENTER] to stop adding drivers." | |
driver_name = gets.chomp | |
if driver_name == "" | |
break | |
else | |
new_car = RaceCar.new(driver_name) | |
@cars << new_car | |
end | |
end | |
puts "All racecars are ready! Time for the race to start!" | |
puts | |
end | |
def start_race | |
@time = 0 | |
puts "--- THE RACE HAS STARTED! ---" | |
puts "There are currently #{@cars.length} cars on the track:" | |
@cars.each { |car| puts "#{car.name} started out going #{car.speed} MPH" } | |
while @time < 5 | |
puts "Press [ENTER] to move forward ONE HOUR in the race." | |
gets.chomp | |
# binding.pry | |
# @cars.map! { |car| car.total_distance += car.speed } | |
@cars.each_with_index { |car, index| @cars[index].total_distance += @cars[index].speed } | |
@cars.each_with_index { |car, index| @cars[index].speed += car.set_new_random_speed } | |
# binding.pry | |
@time += 1 | |
# @cars.map! { |car| car.speed += set_new_random_speed } | |
puts "--- HOUR #{@time} ---" | |
puts "After #{@time} hour(s), this is the current status:" | |
@cars.each { |car| puts "#{car.name} has accumulated #{car.total_distance} total miles and is now moving at #{car.speed}" } | |
end | |
end | |
def determine_winner | |
# sorted_cars = @cars.sort_by { |car| car.total_distance } | |
puts | |
puts "--- RACE OVER! ---" | |
winner = @cars.max_by { |car| car.total_distance } | |
puts "The winner is: #{winner.name} with a total distance of #{winner.total_distance} miles!" | |
end | |
end | |
class RaceCar | |
attr_accessor :name, :speed, :total_distance | |
def initialize(name) | |
@name = name | |
@speed = rand(60..80) | |
@total_distance = 0 | |
end | |
def set_new_random_speed | |
rand(0..20) | |
end | |
end | |
while true | |
race = RaceTrack.new | |
race.setup_race | |
race.start_race | |
race.determine_winner | |
puts "Would you like to play again? [Y]. Any other key will end game." | |
play_again = gets.chomp | |
if play_again == "Y" | |
else break | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment