UNPKG

1.96 kBtext/coffeescriptView Raw
1# input.coffee
2# blocking input, BASIC style, via http
3#
4# 2012/12/16 by JHR
5
6l8 = require( "l8/lib/l8.js")
7l8.debug false
8http = require( "http")
9url = require( "url")
10
11# IO tools. BASIC style
12
13screen = []
14cls = -> screen = []
15print = (msg) -> screen.push msg
16printnl = (msg) -> print msg + "\n"
17
18PendingResponse = null
19respond = (question) ->
20 return unless PendingResponse
21 PendingResponse.writeHead 200, {'Content-Type': 'text/html'}
22 PendingResponse.end [
23 '<html>'
24 screen.join "<br\>"
25 '<form url="/">'
26 question
27 '<input type="text" name="input">'
28 '<input type="submit">'
29 '</form>'
30 '</html>'
31 ].join '\n'
32 PendingResponse = null
33
34HttpQueue = l8.queue( 1000)
35input = l8.Task (question) ->
36 @step ->
37 respond question
38 HttpQueue.get()
39 @step (req,res) ->
40 @trace "Handling new http request, #{req.method}, #{req.url}"
41 if req.method isnt "GET" or not (req.url is "/" or req.url[1] is "?")
42 res.writeHead 404, {"Content-Type": "text/plain"}
43 res.end "404 Not Found\n"
44 return input question
45 PendingResponse = res
46 data = url.parse( req.url, true).query.input
47 return data if data
48 input question
49http.createServer( HttpQueue.put.bind HttpQueue ).listen process.env.PORT
50
51# Main
52
53l8.task ->
54 @step -> l8.trace "Game is running"
55 @repeat ->
56 round = random = 0
57 @step -> input "Enter a decent number to start a new game"
58 @step (r) ->
59 @continue if (r = parseInt( r) or 0) < 10 or r
60 random = Math.floor Math.random() * r
61 round = 0
62 @repeat ->
63 @step -> input "Guess a number"
64 @step (r) ->
65 round++
66 r = parseInt( r)
67 if r > random then printnl "#{r} is too big"
68 if r < random then printnl "#{r} is too small"
69 if r is random
70 cls()
71 printnl "Win in #{round} rounds! Try again"
72 @break
73 l8.trace "Game is scheduled"
74l8.trace "Game is starting"