用ruby和haskell,分别写一个21点游戏。
时间: 2023-02-22 09:54:10 浏览: 111
以下是 Ruby 的实现:
```
class Card
attr_reader :value
def initialize(value)
@value = value
end
end
class Deck
FACES = %w[2 3 4 5 6 7 8 9 10 J Q K A].freeze
SUITS = %w[♠ ♥ ♦ ♣].freeze
def initialize
@deck = []
SUITS.each do |suit|
FACES.each do |face|
@deck << Card.new("#{face}#{suit}")
end
end
end
def shuffle
@deck.shuffle!
end
def draw
@deck.pop
end
end
class Game
POINTS_MAP = { 'J' => 10, 'Q' => 10, 'K' => 10, 'A' => [1, 11] }.freeze
attr_reader :player_hand, :dealer_hand
def initialize
@deck = Deck.new
@deck.shuffle
@player_hand = []
@dealer_hand = []
2.times do
@player_hand << @deck.draw
@dealer_hand << @deck.draw
end
end
def hit
@player_hand << @deck.draw
end
def play_dealer
while points(@dealer_hand) < 17
@dealer_hand << @deck.draw
end
end
def points(hand)
hand.map(&:value).reduce(0) do |sum, value|
face = value[0..-2]
if POINTS_MAP.key?(face)
if POINTS_MAP[face].is_a?(Array)
sum + POINTS_MAP[face][1]
else
sum + POINTS_MAP[face]
end
else
sum + face.to_i
end
end
end
def winner
player_points = points(@player_hand)
dealer_points = points(@dealer_hand)
if player_points > 21
:dealer
elsif dealer_points > 21
:player
elsif dealer_points > player_points
:dealer
elsif player_points > dealer_points
:player
else
:tie
end
end
def display
puts "Player has: #{@player_hand.map(&:value).join(', ')}. Total: #{points(@player_hand)}"
puts "Dealer has: #{@dealer_hand.first.value}, [hidden]"
end
end
game = Game.new
game.display
while game.points(game.player_hand) < 21
puts "Do you want to hit or stay? (h/s)"
input = gets.chomp
break if input == 's'
game.hit
game.display
end
if game.points(game.player_hand) > 21
puts "You busted!"
else
game.
阅读全文