-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgame.rb
74 lines (55 loc) · 1.53 KB
/
game.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require "active_record"
EMPTY_BOARD = [
[" ", " ", " "],
[" ", " ", " "],
[" ", " ", " "],
]
WINNING_SPACES =
[
# Horizontal
[[0, 0], [0, 1], [0, 2]],
[[1, 0], [1, 1], [1, 2]],
[[2, 0], [2, 1], [2, 2]],
# Vertical
[[0, 0], [1, 0], [2, 0]],
[[0, 1], [1, 1], [2, 1]],
[[0, 2], [1, 2], [2, 2]],
# Diagonal
[[0, 0], [1, 1], [2, 2]],
[[0, 2], [1, 1], [2, 0]],
]
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'db.sqlite3'
)
ActiveRecord::Schema.define do
create_table :games do |t|
t.text :board
t.string :winner, limit: 3
t.timestamps
end
end
class Game < ActiveRecord::Base
serialize :board, Array
def self.new_game
Game.create(board: EMPTY_BOARD)
end
def check_win
self.winner = "X" if WINNING_SPACES.any? { |spaces| spaces.all? { |row, col| self.board[row][col] == "X" } }
self.winner = "O" if WINNING_SPACES.any? { |spaces| spaces.all? { |row, col| self.board[row][col] == "O" } }
self.winner = "TIE" if self.winner.nil? && self.board.flatten.count(' ') == 0
end
def human_move(row, column)
return :invalid if self.board[row][column] != " "
self.board[row][column] = "O"
check_win
return :valid if self.winner
computer_move = GAME_MOVES.find { |move, boards| boards.include?(self.board) }
return :valid unless computer_move
computer_row = computer_move[0][:row]
computer_col = computer_move[0][:col]
self.board[computer_row][computer_col] = "X"
check_win
return :valid
end
end