tttt/tttt.rb
2020-05-22 22:13:24 -04:00

105 lines
2.0 KiB
Ruby

require "socket"
@server = TCPServer.new(5678)
@players = [@server.accept, @server.accept]
@labels = %w[X O]
@board = [[nil] * 3, [nil] * 3, [nil] * 3]
@turn = 0
@winner = nil
def write(msg)
@players[@turn].write(msg)
end
def print_board
position = 0
3.times do |y|
write("+---+---+---+\r\n")
3.times do |row|
3.times do |x|
last = x == 2 ? "|\r\n" : ""
case row
when 0
position = y * 3 + x + 1
write("|#{position} #{last}")
when 1
entry = @board[y][x] || " "
write("| #{entry} #{last}")
when 2
write("| #{last}")
end
end
end
end
write("+---+---+---+\r\n")
end
def get_selection
loop do
write("Select a position:\r\n")
input = @players[@turn].gets
position = input.to_i
if position >= 1 && position <= 9
y = (position - 1) / 3
x = (position - 1) % 3
return x, y if @board[y][x].nil?
end
end
end
def take_turn
print_board
x, y = get_selection
@board[y][x] = @labels[@turn]
print_board
end
def check_win_row(y)
if @board[y][0] && @board[y][0] == @board[y][1] && @board[y][0] == @board[y][2]
return @board[y][0]
end
end
def check_win_col(x)
if @board[0][x] && @board[0][x] == @board[1][x] && @board[0][x] == @board[2][x]
return @board[0][x]
end
end
def check_end
3.times do |i|
if @winner = check_win_row(i)
return
elsif @winner = check_win_col(i)
return
end
end
if @board[0][0] && @board[0][0] == @board[1][1] && @board[0][0] == @board[2][2]
return @winner = @board[0][0]
end
if @board[0][2] && @board[0][2] == @board[1][1] && @board[0][2] == @board[2][0]
return @winner = @board[0][2]
end
end
def print_end
if @winner
win_msg = "#{@winner} wins!"
else
win_msg = "Tie game!"
end
@players.each do |client|
client.write("Game over. #{win_msg}\r\n")
end
end
9.times do
take_turn
@turn ^= 1
check_end
break if @winner
end
print_board
print_end