Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getResult(board)
- local tie = true
- for _, node in ipairs(board) do
- if node == " " then
- tie = false
- break
- end
- end
- if tie then
- return 3
- end
- return (
- (board[1] == board[2] and board[1] == board[3] and board[1] ~= " ") and (board[1] == "X" and 1 or 2) or
- (board[4] == board[5] and board[3] == board[6] and board[4] ~= " ") and (board[4] == "X" and 1 or 2) or
- (board[7] == board[8] and board[7] == board[9] and board[7] ~= " ") and (board[7] == "X" and 1 or 2) or
- (board[1] == board[4] and board[1] == board[7] and board[1] ~= " ") and (board[1] == "X" and 1 or 2) or
- (board[2] == board[5] and board[2] == board[8] and board[2] ~= " ") and (board[2] == "X" and 1 or 2) or
- (board[3] == board[6] and board[3] == board[9] and board[3] ~= " ") and (board[3] == "X" and 1 or 2) or
- (board[1] == board[5] and board[1] == board[9] and board[1] ~= " ") and (board[1] == "X" and 1 or 2) or
- (board[3] == board[5] and board[3] == board[7] and board[3] ~= " ") and (board[3] == "X" and 1 or 2) or
- 0
- )
- end
- function drawBoard(board)
- print (
- board[1] .. " | " .. board[2] .. " | " .. board[3] .. "\n" ..
- board[4] .. " | " .. board[5] .. " | " .. board[6] .. "\n" ..
- board[7] .. " | " .. board[8] .. " | " .. board[9]
- )
- end
- function removeElement(array, element)
- for index, value in ipairs(array) do
- if value == element then
- table.remove(array, index)
- return
- end
- end
- end
- function makeEnemyMove(array)
- local options = {}
- for index, value in ipairs(array) do
- if value == " " then
- table.insert(options, index)
- end
- end
- if #options > 0 then
- array[options[math.random(#options)]] = "O"
- end
- return array
- end
- while true do
- local grid = {" ", " ", " ", " ", " ", " ", " ", " ", " "}
- local result;
- repeat
- drawBoard(grid)
- local choice = tonumber(io.read())
- if grid[choice] == " " then
- grid[choice] = "X"
- end
- grid = makeEnemyMove(grid)
- result = getResult(grid)
- until result > 0
- drawBoard(grid)
- print (
- result == 1 and "You win!" or
- result == 2 and "You lose!" or
- "It's a tie!"
- )
- io.write("Press enter to play again.\n")
- io.read()
- end
Advertisement
Add Comment
Please, Sign In to add comment