local board = { {"1", "|", "2", "|", "3"}, {"-","+","-", "+", "-"}, {"4","|","5", "|", "6"}, {"-","+","-", "+", "-"}, {"7","|","8", "|", "9"} }
local currentPlayer = "X"

function drawBoard(list)
	for row, rowlist in ipairs(list) do
	  for column, columnlist in ipairs(rowlist) do
			term.write(columnlist)
	  end
	  print()
	end
end

function toggleTurns()
	if currentPlayer == "X" then
		currentPlayer = "O"
	else
		currentPlayer = "X"
	end
end

function checkWin()

	if board[1][1] == "X" and board[1][3] == "X" and board[1][5] == "X" or board[3][1] == "X" and board[3][3] == "X" and board[3][5] == "X" or board[5][1] == "X" and board[5][3] == "X" and board[5][5] == "X" or board[5][1] == "X" and board[5][3] == "X" and board[5][5] == "X" or board[1][1] == "X" and board[3][3] == "X" and board[5][5] == "X" or board[1][5] == "X" and board[3][3] == "X" and board[5][1] == "X" then
		term.clear()
		term.setCursorPos(1, 1)
		drawBoard(board)
		print("Player X Won!")
		os.sleep(100)
	end
	
	if board[1][1] == "O" and board[1][3] == "O" and board[1][5] == "O" or board[3][1] == "O" and board[3][3] == "O" and board[3][5] == "O" or board[5][1] == "O" and board[5][3] == "O" and board[5][5] == "O" or board[5][1] == "O" and board[5][3] == "O" and board[5][5] == "O" or board[1][1] == "O" and board[3][3] == "O" and board[5][5] == "O" or board[1][5] == "O" and board[3][3] == "O" and board[5][1] == "O" then
		term.clear()
		term.setCursorPos(1, 1)
		drawBoard(board)
		print("Player O Won!")
		os.sleep(100)
	end
	
	if board[1][1] ~= "1" and board[1][3] ~= "2" and board[1][5] ~= "3" and board[3][1] ~= "4" and board[3][3] ~= "5" and board[3][5] ~= "6" and board[5][1] ~= "7" and board[5][3] ~= "8" and board[5][5] ~= "9" then
		term.clear()
		term.setCursorPos(1, 1)
		drawBoard(board)
		print("Draw")
		os.sleep(100)
	end

end


while true do
	term.clear()
	term.setCursorPos(1, 1)
	drawBoard(board)
	write("Player ")
	write(currentPlayer)
	write(", Input a number between 1-9: ")
	local pos = read()

	if pos == "1" and board[1][1] == "1" then
		board[1][1] = currentPlayer
		toggleTurns()
	end
	if pos == "2" and board[1][3] == "2" then
		board[1][3] = currentPlayer
		toggleTurns()
	end
	if pos == "3" and board[1][5] == "3" then
		board[1][5] = currentPlayer
		toggleTurns()
	end
	if pos == "4" and board[3][1] == "4"then
		board[3][1] = currentPlayer
		toggleTurns()
	end
	if pos == "5" and board[3][3] == "5" then
		board[3][3] = currentPlayer
		toggleTurns()
	end
	if pos == "6" and board[3][5] == "6" then
		board[3][5] = currentPlayer
		toggleTurns()
	end
	if pos == "7" and board[5][1] == "7" then
		board[5][1] = currentPlayer
		toggleTurns()
	end
	if pos == "8" and board[5][3] == "8" then
		board[5][3] = currentPlayer
		toggleTurns()
	end
	if pos == "9" and board[5][5] == "9" then
		board[5][5] = currentPlayer
		toggleTurns()
	end
	checkWin()
end