-
Notifications
You must be signed in to change notification settings - Fork 1
/
chess.rb
129 lines (102 loc) · 2.31 KB
/
chess.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
require 'sinatra'
require 'sinatra/reloader'
require './chessdesk'
require './chess_move'
require 'data_mapper'
DataMapper.setup(:default, ENV['DATABASE_URL'] ||
"sqlite3://#{Dir.pwd}/chess.db")
class Piece
include DataMapper::Resource
property :id, Serial
property :x, Integer
property :y, Integer
belongs_to :type
end
class Type
include DataMapper::Resource
property :id, Serial
property :type, String
property :colour, String
property :path, String
has n, :pieces
end
DataMapper.finalize
TYPES = ['rook', 'knight', 'bishop', 'queen',
'king', 'bishop', 'knight', 'rook', 'pawn']
def chess_init
Piece.all.each do |piece|
piece.destroy
end
[[1, 'black'], [6, 'white']].each do |y, colour|
(0..7).each do |x|
Piece.create(
x: x,
y: y,
type: Type.first(colour: colour, type: "pawn")
)
end
end
[[0, 'black'], [7, 'white']].each do |y, colour|
TYPES.select{|x| x != 'pawn'}.each_with_index do |type, x|
Piece.create(
x: x,
y: y,
type: Type.first(colour: colour, type: type)
)
end
end
end
def types_init
Type.all.each do |type|
type.destroy
end
TYPES.each do |type|
['white', 'black'].each do |colour|
Type.create(
colour: colour,
type: type,
path: "pieces/#{type}_#{colour}.png"
)
end
end
end
def init
DataMapper.auto_migrate!
types_init
chess_init
end
get '/' do
pieces = Piece.all.to_a
erb(:'index.html', locals: {pieces: pieces,
selected: nil,
miss: false})
end
post '/' do
pieces = Piece.all.to_a
x = params['cell'][0].to_i
y = params['cell'][2].to_i
piece = nil
pieces.each do |p|
if p.x == x and p.y == y
piece = p
end
end
erb(:'index.html', locals: {pieces: pieces,
selected: piece,
miss: piece == nil})
end
post '/move/:id' do
selected = Piece.get(params[:id].to_i)
x = params['cell'][0].to_i
y = params['cell'][2].to_i
desk = [[nil].cycle.take(8)].cycle.take(8)
Piece.all.each do |p|
desk[p.y][p.x] = p
end
chess_move(desk, selected, [x, y])
redirect to('/')
end
post '/new_game' do
chess_init
redirect to('/')
end