-- Wrap monitor
local monitor = peripheral.wrap("monitor_1")
monitor.clear()
monitor.setTextScale(2)
-- Board setup
local board = {
{" "," "," "},
{" "," "," "},
{" "," "," "}
}
local currentPlayer = "X"
local colorsMap = {X = colors.red, O = colors.blue}
-- Monitor dimensions
local width, height = monitor.getSize()
local topMargin = 3
local cellWidth = math.floor(width / 3)
local cellHeight = math.floor((height - topMargin) / 3)
-- Draw the grid and board
local function drawBoard()
monitor.clear()
monitor.setTextColor(colors.white)
monitor.setCursorPos(1,1)
monitor.write("=== Tic-Tac-Toe ===")
-- Draw grid lines
for i = 1, 2 do
-- Vertical lines
local x = i * cellWidth + 1
for y = topMargin, height do
monitor.setCursorPos(x, y)
monitor.write("|")
end
-- Horizontal lines
local y = topMargin + i * cellHeight - 1
monitor.setCursorPos(1, y)
monitor.write(string.rep("-", width))
end
-- Draw X and O
for r = 1, 3 do
for c = 1, 3 do
local x = (c - 1) * cellWidth + math.floor(cellWidth / 2)
local y = topMargin + (r - 1) * cellHeight + math.floor(cellHeight / 2)
monitor.setCursorPos(x, y)
monitor.setTextColor(colorsMap[board[r][c]] or colors.white)
monitor.write(board[r][c])
end
end
-- Display current player
monitor.setTextColor(colors.white)
monitor.setCursorPos(1, height)
monitor.write("Player "..currentPlayer.."'s turn ")
end
-- Check for win
local function checkWin()
for i=1,3 do
if board[i][1] ~= " " and board[i][1] == board[i][2] and board[i][2] == board[i][3] then return true end
if board[1][i] ~= " " and board[1][i] == board[2][i] and board[2][i] == board[3][i] then return true end
end
if board[1][1] ~= " " and board[1][1] == board[2][2] and board[2][2] == board[3][3] then return true end
if board[1][3] ~= " " and board[1][3] == board[2][2] and board[2][2] == board[3][1] then return true end
return false
end
-- Check for draw
local function checkDraw()
for r=1,3 do
for c=1,3 do
if board[r][c] == " " then return false end
end
end
return true
end
-- Convert touch coordinates to row/column
local function touchToCell(x, y)
local col = math.ceil(x / cellWidth)
local row = math.ceil((y - topMargin + 1) / cellHeight)
if row < 1 then row = 1 end
if row > 3 then row = 3 end
if col < 1 then col = 1 end
if col > 3 then col = 3 end
return row, col
end
-- Main loop
drawBoard()
while true do
local event, side, x, y = os.pullEvent("monitor_touch")
local row, col = touchToCell(x, y)
if row >= 1 and row <= 3 and col >= 1 and col <= 3 then
if board[row][col] == " " then
board[row][col] = currentPlayer
drawBoard()
if checkWin() then
monitor.setCursorPos(1, height)
monitor.setTextColor(colors.green)
monitor.write("Player "..currentPlayer.." wins! ")
break
elseif checkDraw() then
monitor.setCursorPos(1, height)
monitor.setTextColor(colors.yellow)
monitor.write("It's a draw! ")
break
else
currentPlayer = (currentPlayer == "X") and "O" or "X"
drawBoard()
end
end
end
end