> webscript
Home
Scripts
Cron Jobs
Examples
Documentation
Pricing
Help/Support
Blog
Login / Signup
Basic examples
Hello, World
Hello, Name
Hello, HTML
Making HTTP requests
File examples
File upload
Email examples
Sending Email
Contact Form
Sending Email Attachments
URL Contents as an Attachment
User authentication
Password Hashing
Twitter Authentication
Storage examples
Counter
Mobile Verification
HTML examples
Generating HTML From a Template
XML examples
Parsing RSS
Weather
Other services
reCAPTCHA
Stripe Payments
Stripe Webhooks
Twilio SMS
Twilio: Receive Texts, Make Calls
Amazon S3 Upload
Windows Azure Blob Upload
Twitter: Sending a Tweet
Monitoring
Heartbeat Monitoring
Website Uptime Monitoring
Gaming
Tic-Tac-Toe
Leaderboard
Tic-Tac-Toe
Script Code
tictactoe.webscript.io/start
local id = math.random(1, 100000) local board = {} for i = 1,9 do board[i] = '' end local state = {board=board, players={X=request.form.secret}} storage['game:'..id] = json.stringify(state) return {id=id, state=state}
tictactoe.webscript.io/join
local pusher = require('pusher') local id = request.form.id local state = json.parse(storage['game:'..id]) if state.players.O ~= nil then return 403 else state.players.O = request.form.secret state.turn = 'X' storage['game:'..id] = json.stringify(state) pusher.send('
', '
', '
', request.form.id, 'update', json.stringify(state)) return state end
tictactoe.webscript.io/move
local pusher = require('pusher') function getwinner(board) local lines = { {1,2,3},{4,5,6},{7,8,9}, -- horizontal wins {1,4,7},{2,5,8},{3,6,9}, -- vertical wins {1,5,9},{3,5,7} -- diagonal wins } for i,line in ipairs(lines) do local winner = nil for i,index in ipairs(line) do winner = winner or board[index] if board[index] == '' or board[index] ~= winner then winner = nil break end end if winner ~= nil then return winner end end return nil end function isfull(board) for i,v in ipairs(board) do if v == '' then return false end end return true end local state = json.parse(storage['game:'..request.form.id]) local index = tonumber(request.form.index) if state.turn ~= request.form.player -- not his turn or request.form.secret ~= state.players[request.form.player] -- imposter or index == nil or index < 1 or index > 9 -- out of range or state.board[index] ~= '' then -- already taken return 403 else state.board[index] = request.form.player winner = getwinner(state.board) if winner ~= nil then state.winner = winner state.turn = nil elseif isfull(state.board) then state.draw = true state.turn = nil else state.turn = ({X='O', O='X'})[request.form.player] end if state.turn == nil then -- game over storage['game:'..request.form.id] = nil else storage['game:'..request.form.id] = json.stringify(state) end pusher.send('
', '
', '
', request.form.id, 'update', json.stringify(state)) return 200 end
Try It!
Start a new game:
Start
or join a game:
Join
×
Log in
Email address:
Password:
Don't have an account yet?
Sign up for free.