-
-
Save sksmatt/2003655 to your computer and use it in GitHub Desktop.
Text-based Pong Game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment