tyler / roomy

a mud engine in ruby

This URL has Read+Write access

roomy / client.rb
100644 84 lines (66 sloc) 1.86 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
require 'client/meta_commands'
require 'client/commands'
 
# Client instances are created by the single server instance running for the MUD.
# A Client instance is created, and registered with the Class. When disconnecting
# Client#destroy is called, thus unregistering it with the Client Class.
class Mud
  class Client
    class << self
      attr_reader :clients
 
      def delete(client)
        @clients.delete(client)
      end
 
      def register(client)
        @clients ||= []
        @clients << client
      end
 
      def message_all(message)
        @clients.each {|c| c.message(message)}
      end
 
      def find_by_character(name)
        name = name.downcase
        @clients.find{|c| c.character.name.downcase == name}
      end
 
      def connect(session)
        Thread.new(session) do |session|
          begin
            client = self.new(session)
 
            client.message("Hey man. Sup?")
 
            client.login
 
            until session.closed? || session.eof? do
              input = session.gets.chomp
              client.commands.dispatch(input)
            end
          rescue => e
            p e
            puts e.backtrace
            puts
          ensure
            client.destroy
          end
        end
      end
 
    end
 
    attr_reader :session,:commands,:character
 
    def initialize(session)
      @session = session
      @commands = Commands.new(self)
      self.class.register(self)
    end
 
    def destroy
      self.class.delete(self)
      @session.close
    end
 
    def message(text)
      @session.puts(text)
    end
 
    def login
      message "Name:"
      name = @session.gets.chomp
 
      destroy unless Character.exist?(name)
      @character = Character.load(name)
      
      message "Password:"
      destroy unless @character.password_matches?(@session.gets.chomp)
    end
  end
end