Skip to content

Instantly share code, notes, and snippets.

@sksmatt
Forked from betawaffle/pong.coffee
Created March 8, 2012 21:42
Show Gist options
  • Save sksmatt/2003655 to your computer and use it in GitHub Desktop.
Save sksmatt/2003655 to your computer and use it in GitHub Desktop.

Revisions

  1. @betawaffle betawaffle created this gist Jun 24, 2011.
    42 changes: 42 additions & 0 deletions pong.coffee
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    util = require 'util'
    after = (time, args..., callback) -> setTimeout callback, time, args...

    class Game
    score: 0
    score_step: 20
    constructor: (@client, @difficulty = 800) ->
    @send 'HELO :Welcome to Pong!'
    @send 'HELP :When you receive a PING <code>,'
    @send 'HELP :reply quickly with PONG <code>,'
    @send 'HELP :or the connection will timeout.'
    @send "INFO difficulty #{@difficulty}"
    @send "INFO score_step #{@score_step}"
    @client.on 'end', => @kill 'Bai!'
    @client.on 'data', @data
    send: (line) => @client.write "#{line}\r\n"
    kill: (quit) => @client.end "\rKTHX #{@score} :#{quit}\r\n"
    data: (data) =>
    return unless @code?
    if m = data.match /^PONG (\d+)/i
    return if m[1] isnt @code
    clearTimeout @timer
    delay = 3000 + Math.floor(Math.random() * 10000)
    after delay, @ping
    @score += 1
    time: =>
    @delay = (@difficulty - @score * @score_step) * (5 + @code.length)
    @timer = after @delay, 'Game Over!', @kill
    @start = new Date().getTime()
    ping: =>
    @code = Math.floor(Math.random() * 9999).toString()
    @time()
    @send "PING #{@code} :Respond within #{@delay / 1000} seconds"

    worker = (client) ->
    client.setEncoding 'utf8'
    client.on 'connect', ->
    game = new Game(this)
    after 5000, game.ping
    server = require('net').createServer allowHalfOpen: true, worker
    server.listen 7664
    # Listen on PONG