Commit 84143c7e by Nick An

mass init

parent 29b570c6
require 'faye/websocket'
require 'rack'
require 'thin'
require 'json'
module CrazyFlirt
class RandomKeyGenerator
WORDS = %w(a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 0)
SIZE = WORDS.size
def self.key
words = ::CrazyFlirt::RandomKeyGenerator::WORDS
size = ::CrazyFlirt::RandomKeyGenerator::SIZE - 1
random_key = ''
random = Random.new
5.times do
random_key += words[random.rand(0..size)]
end
Time.now.to_s.to_i + random_key
end
end
class RandomRole
def initialize
@roles = %i(ghost runner runner runner)
end
def pick_role
size = @roles.size - 1
index = Random.new.rand(0..size)
role = @roles[index]
@roles.delete_at(index)
role
end
end
class Client
attr_reader :key
attr_accessor :role
def initialize(ws)
@ws = ws
@key = generate_key
@role = nil
end
def msg(msg)
@ws.send(msg.to_json)
end
private
def generate_key
CrazyFlirt::RandomKeyGenerator.key
end
end
class GameRoom
attr_reader :clients
def initialize(name)
@clients = {}
@name = name
@status = :waiting
end
def set_client(client)
@clients[client.key] = client
end
def start!
@status = :start
end
def leave_client(key)
@clients.delete(key)
end
end
class SocketEngine
def initialize
Faye::WebSocket.load_adapter('thin')
@faye = Faye::WebSocket
@socket_pool = {}
@room_pool = {}
end
def call(env)
return unless @faye.websocket?(env)
ws = @faye.new(env)
ws.on :message do |event|
ws.send(event.data)
message = JSON.parse(event.data)
seq = message[:seq]
command(seq, message)
end
ws.on :close do |event|
puts 'closed'
end
ws.rack_response
end
private
def commend(command, *args)
send(command, *args)
end
def clicking
room = @room_pool[msg['room_id']]
room.clients.each do |client|
next if client.key == msg
client.msg(msg)
end
end
def moving(msg)
room = @room_pool[msg['room_id']]
room.clients.each do |client|
next if client.key == msg
client.msg(msg)
end
end
def create_room(msg)
client_id = msg['cid']
key = "room_#{::CrazyFlirt::RandomKeyGenerator.key}"
room = GameRoom.new(key)
@room_pool[key] = room
client = @socket_pool[client_id]
room.set_client(client)
client.msg(room_id: key)
end
end
end
Rack::Handler.get('thin').run(CrazyFlirt::SocketEngine.new, Host: '192.168.50.118', Port: 80)
\ No newline at end of file
require 'sinatra'
set :bind, '192.168.50.118'
set :port, 1234
get '/hello' do
'hello'
end
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment