Skip to content

Instantly share code, notes, and snippets.

@hanachin
Last active December 13, 2024 02:29
Show Gist options
  • Save hanachin/324c4215bb107a27edae5b75948c8ae5 to your computer and use it in GitHub Desktop.
Save hanachin/324c4215bb107a27edae5b75948c8ae5 to your computer and use it in GitHub Desktop.
https://adventar.org/calendars/10360 の13日目です。 https://it-college.slack.com/archives/C07MPKKSQ3C/p1733972206637199 をRubyで書いてみました。Rubyはいいぞ。
CHO = "丁"
HAN = "半"
class SixSidedDice
attr_reader :number
def roll
@number = rand(1..6)
end
end
class Result
attr_reader :cho_or_han, :total
def initialize(dice)
@numbers = dice.map(&:number)
@total = @numbers.sum
@cho_or_han = @total.even? ? CHO : HAN
end
def show
@numbers.each.with_index(1) do |num, n|
puts "さいころ#{n}の目:#{num}"
end
puts "さいころの目の合計:#{@total}"
puts "結果:#{@cho_or_han}"
end
end
Cup = Data.define(:dice) do
def shake = dice.each(&:roll)
def open = Result.new(dice)
end
Player = Data.define(:name) do
def make_bet
case gets.to_i
in 1
HAN
in 2
CHO
end
rescue NoMatchingPatternError
retry
end
end
class Mat
def initialize = cleanup
def balanced? = !too_much_cho? && !too_much_han?
def place_on(bet, player) = @mat[bet] << player
def players_on(bet) = @mat[bet]
def too_much_cho? = cho - han > 1
def too_much_han? = han - cho > 1
def cleanup
@mat = { CHO => [], HAN => [] }
end
private
def cho = @mat[CHO].size
def han = @mat[HAN].size
end
class Game
def initialize(players)
raise ArgumentError if players.size < 2
@players = players
@cup = Cup.new([SixSidedDice.new, SixSidedDice.new])
@mat = Mat.new
@score_by_player = players.to_h {|player| [player, 0] }
end
# よくないですか???
def play
shake_cup
begin
cleanup_mat
make_bet
end until balanced?
open_cup
show_result
update_score
show_score
end
private
def balanced?
if @mat.too_much_cho?
puts "半方ないか?"
elsif @mat.too_much_han?
puts "丁方ないか?"
end
@mat.balanced?
end
def cleanup_mat
@mat.cleanup
end
def make_bet
@players.each do |player|
print "#{player.name}さん、半か丁か?(press key 1 or 2) "
bet = player.make_bet
puts "#{player.name}さんの予想: #{bet}"
@mat.place_on(bet, player)
end
end
def open_cup
@result = @cup.open
end
def shake_cup
@cup.shake
puts "さいころを振りました"
end
def show_result
@result.show
end
def show_score
@score_by_player.each do |player, score|
puts "#{player.name}さんのスコア:#{score}"
end
end
def update_score
@mat.players_on(@result.cho_or_han).each do |player|
@score_by_player[player] += @result.total
end
end
end
def get_player_names(num)
1.upto(num).map do |n|
print "プレイヤー#{n}の名前を入力してください: "
gets.chomp
end
end
def print_separator
puts "-" * 32
puts
end
PLAYER_NUM = 2
names = get_player_names(PLAYER_NUM)
print_separator
players = names.map {|name| Player.new(name:) }
game = Game.new(players)
loop do
game.play
print_separator
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment