Last active
March 8, 2023 16:30
-
-
Save JoshDevHub/cbac15e76142f79fd83d5fe75f87a614 to your computer and use it in GitHub Desktop.
Observable Example with TTT
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
require "observer" | |
class Board | |
include Observable | |
def initialize | |
@grid = [" "] * 9 | |
end | |
def to_s | |
separator = "\n---+---+---\n" | |
Array.new(3) { row_for(_1) }.join(separator) | |
end | |
def place_marker(position, marker) | |
index_position = position.to_i - 1 | |
if index_position && @grid[index_position] == " " | |
@grid[index_position] = marker | |
changed | |
end | |
end | |
def broadcast_state | |
notify_observers(to_s) | |
end | |
private | |
def row_for(index) | |
first, second, third = @grid.each_slice(3).to_a[index] | |
" #{first} | #{second} | #{third}" | |
end | |
end | |
class Display | |
def update(board_string) | |
system("clear") | |
puts board_string | |
end | |
end | |
b = Board.new | |
d = Display.new | |
b.add_observer(d) | |
curr_marker = "X" | |
loop do | |
print "Enter your input >> " | |
input = gets.chomp | |
b.place_marker(input, curr_marker) | |
if b.changed? | |
b.broadcast_state | |
curr_marker = curr_marker == "X" ? "O" : "X" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment