Created
December 31, 2016 10:58
-
-
Save ardbytes/5a2b7191cb8bb3172badc960a36038c8 to your computer and use it in GitHub Desktop.
TicTacToe
This file contains 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
PLAYER_SYMBOL = "X" | |
COMPUTER_SYMBOL = "O" | |
WINNING_COMBINATION = | |
{ | |
0 => [[0, 1, 2], [0, 3, 6], [0, 4, 8]], | |
1 => [[0, 1, 2], [1, 4, 7]], | |
2 => [[0, 1, 2], [2, 5, 8], [2, 4, 6]], | |
3 => [[0, 3, 6], [3, 4, 5]], | |
4 => [[0, 4, 8], [3, 4, 5], [2, 4, 6], [1, 4, 7]], | |
5 => [[3, 4, 5], [2, 5, 8]], | |
6 => [[0, 3, 6], [2, 4, 6], [6, 7, 8]], | |
7 => [[1, 4, 7], [6, 7, 8]], | |
8 => [[0, 4, 8], [6, 7, 8], [2, 5, 8]] | |
} | |
def computer(boxes) | |
b = boxes.find {|b| b.text.length == 0} | |
if b | |
b.text = COMPUTER_SYMBOL | |
end | |
end | |
def game_over?(boxes) | |
has_winner?(boxes) || all_filled?(boxes) | |
end | |
def has_winner?(boxes) | |
winning_symbol(boxes) | |
end | |
def all_filled?(boxes) | |
boxes.all? {|b| b.text.length > 0} | |
end | |
def announce_winner(boxes) | |
s = winning_symbol(boxes) | |
if s == COMPUTER_SYMBOL | |
alert('COMPUTER WINS;') | |
elsif s == PLAYER_SYMBOL | |
alert('YOU WIN!') | |
else | |
alert('DRAW') | |
end | |
end | |
def winning_symbol(boxes) | |
s = WINNING_COMBINATION.find do |idx, combinations| | |
combinations.find do |combination| | |
x = combination.collect do |i| | |
boxes[i].text | |
end | |
x.uniq.length == 1 && x.uniq.first != '' | |
end | |
end | |
if s | |
boxes[s.flatten.first].text | |
end | |
end | |
def all_clear(boxes) | |
boxes.each do |box| | |
box.text = '' | |
end | |
end | |
def button_clicked(boxes, i) | |
if boxes[i].text.length == 0 | |
boxes[i].text = PLAYER_SYMBOL | |
end | |
computer(boxes) | |
if game_over?(boxes) | |
announce_winner(boxes) | |
all_clear(boxes) | |
end | |
end | |
Shoes.app(:title => 'TicTacToe') do | |
boxes = [] | |
buttons = [] | |
9.times do | |
boxes << edit_box() | |
end | |
9.times do |i| | |
buttons << button("X", :width => 200) | |
end | |
buttons.each_with_index do |button, index| | |
button.click do | |
button_clicked(boxes, index) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment