Last active
December 15, 2015 12:17
-
-
Save tyamagu2/79787239aaa7ed2e83fc to your computer and use it in GitHub Desktop.
reversi
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
class Board | |
def initialize(size = 8) | |
@size = size | |
@board = [] | |
@size.times do | |
row = [] | |
@size.times { row << :none } | |
@board << row | |
end | |
c = @size / 2 | |
@board[c - 1][c - 1] = :black | |
@board[c][c] = :black | |
@board[c - 1][c] = :white | |
@board[c][c - 1] = :white | |
end | |
def place(color, x, y) | |
return [0, 'out of bounds'] if x < 0 || y < 0 || x >= @size || y >= @size | |
return [0, 'occupied'] if @board[y][x] != :none | |
opposite_color = color == :black ? :white : :black | |
total_reversed = 0 | |
[[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]].each do |dy, dx| | |
nx = x + dx | |
ny = y + dy | |
count = 0 | |
while nx >= 0 && ny >= 0 && nx < @size && ny < @size && @board[ny][nx] == opposite_color | |
nx += dx | |
ny += dy | |
count += 1 | |
end | |
next if count == 0 | |
next unless @board[ny][nx] == color | |
total_reversed += count | |
rdx = -1 * dx | |
rdy = -1 * dy | |
while nx != x || ny != y | |
@board[ny][nx] = color | |
nx += rdx | |
ny += rdy | |
end | |
end | |
if total_reversed == 0 | |
return [0, 'cannot reverse anything'] | |
end | |
@board[y][x] = color | |
[total_reversed, 'ok'] | |
end | |
def show | |
puts " |#{(0..(@size - 1)).to_a.join('|')}|" | |
@size.times do |y| | |
row = @board[y].map { |cell| cell_to_char(cell) }.join('|') | |
puts "#{y}|#{row}|" | |
end | |
puts '-' * 17 | |
end | |
private | |
def cell_to_char(cell) | |
case cell | |
when :none then ' ' | |
when :black then '*' | |
when :white then 'o' | |
end | |
end | |
end | |
board = Board.new | |
board.show | |
turn = :black | |
puts turn | |
while (str = gets) | |
x, y = str.chomp.split.map(&:to_i) | |
reversed, msg = board.place(turn, x, y) | |
if reversed > 0 | |
turn = turn == :black ? :white : :black | |
board.show | |
else | |
puts msg | |
end | |
puts turn | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
振り返り中に fail じゃなくてエラーメッセージを表示するようにしました