Created
October 11, 2008 14:09
-
-
Save hitode909/16269 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# /usr/bin/ruby | |
# -*- coding: utf-8 -*- | |
# オセロの石を置くプログラム | |
# based on http://bkc.g.hatena.ne.jp/coconutsfine/20081010/1223651539 | |
# 新しい盤面のArrayを作って返す | |
def setup_box | |
# 盤面オブジェクトを生成(8x8の:empty) | |
box = Array.new(8){ Array.new(8, :empty) } | |
#盤面の初期値を設定 | |
set_box(box, [3,3], :black) | |
set_box(box, [4,4], :black) | |
set_box(box, [3,4], :white) | |
set_box(box, [4,3], :white) | |
box | |
end | |
# 盤面を表示する | |
# box: 盤面 | |
def print_box(box) | |
rule = { :empty, ' ', :white, '○', :black, '●'} | |
puts " a b c d e f g h" | |
puts " ┌─┬─┬─┬─┬─┬─┬─┬─┐" | |
line_counter = 1 | |
box.each do |line| | |
print line_counter | |
line.each do |cell| | |
print "|#{rule[cell]}" | |
end | |
puts '|' | |
if line_counter <= 7 | |
puts " ├─┼─┼─┼─┼─┼─┼─┼─┤" | |
else | |
puts " └─┴─┴─┴─┴─┴─┴─┴─┘" | |
end | |
line_counter+=1 | |
end | |
end | |
# 入力された座標が盤の範囲内か調べる | |
# point: 座標([x, y]) | |
def in_box?(point) | |
point.size == 2 and (0..7).include?(point[0]) and (0..7).include?(point[1]) | |
end | |
# 入力された座標が盤の範囲内か調べる | |
# box: 盤面 | |
# point: 座標([x, y]) | |
def get_box(box, point) | |
if in_box?(point) | |
x, y = point[0], point[1] | |
box[x][y] | |
else | |
raise "範囲外のpointです" | |
end | |
end | |
# 指定された座標の内容を変更する | |
# box: 盤面 | |
# point: 座標([x, y]) | |
# color: 置く石の色(:white, :black, :empty) | |
def set_box(box, point, color) | |
rule = [:white, :black, :empty] | |
if in_box?(point) | |
if rule.include?(color) | |
x, y = point[0], point[1] | |
box[x][y]= color | |
box | |
else | |
raise "想定外の何かを置こうとしています(#{color})" | |
end | |
else | |
raise "範囲外のpointです" | |
end | |
end | |
# 誰のターンかを返す | |
# counter: 何ターン目か | |
def get_turn(counter) | |
counter %2 == 0 ? :white : :black | |
end | |
# main | |
rolecounter = 0 # 石を打つたびにインクリメントするカウンタ | |
box = setup_box # 盤面のオブジェクト | |
# メインループ | |
loop do | |
# 盤面を表示 | |
print_box(box) | |
# 石を打つまでループ | |
loop do | |
puts "#{get_turn(rolecounter)}のターン" | |
puts "オセロを置きたい場所を入力してください(例:3 d)" | |
print "> " | |
input=gets.chomp.split(" ") | |
if input.size != 2 | |
puts "入力形式が不自然です" | |
redo | |
end | |
# 入力された座標を整形 | |
point = [input[0].to_i-1, input[1][0]-"a"[0] ] | |
unless in_box?(point) | |
puts "盤外です" | |
redo | |
end | |
if get_box(box, point) != :empty | |
puts "既に石が置かれています" | |
redo | |
end | |
set_box(box, point, get_turn(rolecounter) ) # 石を置く | |
rolecounter += 1 # カウンタを進める | |
break | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment