Skip to content

Instantly share code, notes, and snippets.

@madogiwa0124
Last active May 30, 2017 02:40
Show Gist options
  • Save madogiwa0124/ea33136194cb4e4d3f04428ed598e790 to your computer and use it in GitHub Desktop.
Save madogiwa0124/ea33136194cb4e4d3f04428ed598e790 to your computer and use it in GitHub Desktop.
じゃんけんシミュレーター(作成中)
# 定数
HAND = ["p", "r", "s"] # r:グー、s:チョキ、p:パー
class Player
attr_accessor :id, :hand, :lose_flg, :rank
def initialize(id)
@id = id
@hand = ""
@lose_flg = false
@rank = nil
end
def reset
set_hand
@lose_flg = false
end
def set_hand
@hand = HAND[rand(3)]
end
end
def judge(hands)
case hands.sort
when ["p","r"] then HAND[0] # パー VS グー
when ["p","s"] then HAND[2] # パー VS チョキ
when ["r","s"] then HAND[1] # グー VS チョキ
end
end
# じゃんけんメソッド
# input : players(参加者)
# output : 勝った参加者、負けた参加者
def battle(players)
# 手の初期化
players.each{ |player| player.reset }
hands = players.map{ |player| player.hand }
# 出された手が一種類または3種類の場合は、再実行(あいこ)
if hands.uniq.length == 2
win_hand = judge(hands.uniq)
players.each{ |player| player.lose_flg = true unless player.hand == win_hand }
else
battle(players)
end
# 勝ち組と負け組みに分ける
win_g = players.select{ |player| !player.lose_flg && !player.rank }
lose_g = players.select{ |player| player.lose_flg && !player.rank }
# return { win_g: win_g, lose_g: lose_g }
return win_g
end
rank_cnt = 1
continue_flg = true
players = []
hands = []
player_N, simulation_N = gets.to_i, gets.to_i
player_N.times { |i| players << Player.new(i) }
i = 0
while !players.select{ |player| !player.rank }.empty?
players = players.select{ |player| !player.rank }
result = battle(players)
if result.length == 1
champ = result[0]
players[champ.id].rank = rank_cnt
rank_cnt += 1
end
end
p players
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment