Code: Select all
require('lib.lquery')
E:new(screen):draw(function() --draw field
for i = 1, 4 do
G.line(250, 50 + i*100, 550, 50 + i*100)
G.line(150 + i*100, 150, 150 + i*100, 450)
end
end)
G.setFont(30) --text ontop
text = E:new(screen):text('', 12, 'center'):size(800,16)
local move = true --current move: true - crossess, false - noughts
local win = false --if someone wins this becomes true
moves = 0 --moves count
local cell_draw = function(s) --cell drawing function
if s.cell == true then --this is cross
G.line(s.x + 20, s.y + 20, s.x + 80, s.y + 80)
G.line(s.x + 80, s.y + 20, s.x + 20, s.y + 80)
elseif s.cell == false then --this is nought
G.circle('line', s.x + 50, s.y + 50, 32, 32)
end
end
local check_win = function() --checks, if someone wins the game
local a = cells._child
local winner
local function b(i) return a[i].cell end
for i = 1, 3 do --check rows (three in row)
if b(i) ~= nil and b(i) == b(i+3) and b(i) == b(i+6) then
winner = b(i)
elseif b((i-1)*3+1) ~= nil and b((i-1)*3+1) == b((i-1)*3+2) and b((i-1)*3+1) == b((i-1)*3+3) then
winner = b((i-1)*3+1)
end
end
--check two diagonals
if b(1) ~= nil and b(1) == b(5) and b(1) == b(9) then
winner = b(1)
elseif b(3) ~= nil and b(3) == b(5) and b(3) == b(7) then
winner = b(3)
end
if winner ~= nil then
text.text = (winner and 'You win!' or 'Computer wins!')
win = true
end
if win == false and moves == 9 then
win = true
text.text = 'Draw!'
end
end
local ai = function() --simple artificial intelligence
local n = 0
repeat
n = math.random(1,9) --just random:)
until cells._child[n].cell == nil
cell_click(cells._child[n])
end
cell_click = function(s) --click handler
if win == false then
if s.cell ~= true and s.cell ~= false then
moves = moves + 1
s.cell = move
move = not move
check_win() --checks, if someone wins
if move == false and win == false then ai() end --run ai
end
else --restart game if someone wins and player clicks on the field
for i = 1, 9 do cells._child[i].cell = nil end
text.text = ''
move = true
win = false
moves = 0
end
end
cells = E:new(screen) --create cells
for i = 1, 3 do
for j = 1, 3 do
E:new(cells):move(150 + j * 100, 50 + i * 100):size(100, 100)
:click(cell_click):draw(cell_draw) --click and draw callbacks
end
end