Class: Mjai::TCPClientGame

Inherits:
Game
  • Object
show all
Defined in:
lib/mjai/tcp_client_game.rb

Instance Attribute Summary

Attributes inherited from Game

#all_pais, #bakaze, #current_action, #dora_markers, #honba, #last, #num_pipais, #oya, #players, #previous_action

Instance Method Summary collapse

Methods inherited from Game

#action_in_view, #can_kan?, #distance, #do_action, #doras, #dump_action, #first_turn?, #get_hora, #on_action, #on_responses, #ranked_players, #render_board, #update_state, #validate, #validate_fields_exist, #validate_response_content, #validate_response_type, #validate_responses

Constructor Details

#initialize(params) ⇒ TCPClientGame

Returns a new instance of TCPClientGame.



16
17
18
19
# File 'lib/mjai/tcp_client_game.rb', line 16

def initialize(params)
  super()
  @params = params
end

Instance Method Details

#expect_response_from?(player) ⇒ Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/mjai/tcp_client_game.rb', line 58

def expect_response_from?(player)
  return player.id == @my_id
end

#playObject



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
# File 'lib/mjai/tcp_client_game.rb', line 21

def play()
  uri = URI.parse(@params[:url])
  TCPSocket.open(uri.host, uri.port) do |socket|
    socket.sync = true
    socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
    socket.each_line() do |line|
      puts("<-\t%s" % line.chomp())
      action_json = line.chomp()
      action_obj = JSON.parse(action_json)
      case action_obj["type"]
        when "hello"
          response_json = JSON.dump({
              "type" => "join",
              "name" => @params[:name],
              "room" => uri.path.slice(/^\/(.*)$/, 1),
          })
        when "error"
          break
        else
          if action_obj["type"] == "start_game"
            @my_id = action_obj["id"]
            self.players = Array.new(4) do |i|
              i == @my_id ? @params[:player] : PuppetPlayer.new()
            end
          end
          action = Action.from_json(action_json, self)
          responses = do_action(action)
          break if action.type == :end_game
          response = responses && responses[@my_id]
          response_json = response ? response.to_json() : JSON.dump({"type" => "none"})
      end
      puts("->\t%s" % response_json)
      socket.puts(response_json)
    end
  end
end