Last active
July 20, 2016 03:04
-
-
Save vector623/ebe017407c6f55f6f4a0bcd66a1d38f4 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 'net/http' | |
require 'nokogiri' | |
#you need Nokogiri for this to work: gem install 'nokogiri' | |
#fetch html if not cached | |
html_cache_file = 'blackjack-chart.html' | |
if File.exist? html_cache_file | |
html = File.read(html_cache_file) | |
else | |
html = Net::HTTP.get(URI.parse('http://www.blackjack-chart.com/')) | |
File.write(html_cache_file, html) | |
end | |
#extract strategy matrix from html | |
strategy_matrix = Nokogiri::HTML(html). | |
css('table#tablepress-3 tr'). | |
drop(1). | |
map{ |tr| | |
tr.css('td'). | |
map{ |td| td.text } | |
} | |
#extract letter to description lookup from html | |
advice_legend = Nokogiri::HTML(html). | |
css('table#tablepress-4 tr'). | |
map{ |tr| tr.css('td') }. | |
map{ |td| [ td[0].text,td[1].text ] }. | |
to_h | |
#extract lookup index for dealer's card from strategy matrix | |
dealer_hand_lookup = strategy_matrix. | |
take(1). | |
flatten. | |
drop(1). | |
each_with_index. | |
map{ |elem,idx| [elem,idx + 1] }. | |
to_h | |
#extract lookup index for player's hand from strategy matrix | |
player_hand_lookup = strategy_matrix. | |
transpose. | |
take(1). | |
flatten. | |
drop(1). | |
each_with_index. | |
map{ |elem,idx| [elem,idx + 1] }. | |
to_h | |
#read input from console. try to do some cleanup | |
puts "What do you have?" | |
player = gets.chomp. | |
upcase. | |
split(","). | |
sort{|x,y| y <=> x }. | |
join(",") | |
puts "What does the dealer have?" | |
dealer = gets.chomp.upcase | |
begin | |
player_index = player_hand_lookup[player] | |
dealer_index = dealer_hand_lookup[dealer] | |
answer = strategy_matrix[player_index][dealer_index] | |
readable_answer = advice_legend[answer] | |
puts readable_answer | |
rescue TypeError => e | |
puts "player hand valid inputs: #{player_hand_lookup.keys}" | |
puts "dealer hand valid inputs: #{dealer_hand_lookup.keys}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment