Skip to content

Instantly share code, notes, and snippets.

@tyamagu2
Last active December 15, 2015 12:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyamagu2/79787239aaa7ed2e83fc to your computer and use it in GitHub Desktop.
Save tyamagu2/79787239aaa7ed2e83fc to your computer and use it in GitHub Desktop.
reversi
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
@tyamagu2
Copy link
Author

振り返り中に fail じゃなくてエラーメッセージを表示するようにしました

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment