Skip to content

Instantly share code, notes, and snippets.

@hungryblank
Created February 20, 2010 11:47
Show Gist options
  • Save hungryblank/309643 to your computer and use it in GitHub Desktop.
Save hungryblank/309643 to your computer and use it in GitHub Desktop.
# A ping pong ball, which pings and pongs properly
class Ball
SOUNDS = %w(ping pong)
def initialize
@hit_count = 0
end
def hit
@hit_count += 1
puts SOUNDS[@hit_count.remainder(2)] + " hit #{@hit_count} times"
end
end
#client player, connects to the server and starts playing
#as soon as it receives the ball from the server
require 'ball'
require 'player'
EM.run {
EM.connect("127.0.0.1", 9797, Player)
}
#ping pong player common behaviour, hit the ball
#sending it to the other end
require 'rubygems'
require 'eventmachine'
module Player
include EM::P::ObjectProtocol
def receive_object(ball)
ball.hit
send_object(ball)
end
def unbind
puts "game stopped"
end
end
#server player, serves the ball to the client as
#soon as a client connects.
#It can play with many clients at the same time
require 'ball'
require 'player'
module ServerPlayer
include Player
def post_init
puts "client connected starting serving ball"
send_object(Ball.new)
end
end
EM.run {
EM.start_server("127.0.0.1", 9797, ServerPlayer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment