~armagetronad-dev/ladle/ladle-export

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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# encoding: utf-8

module Ladle
  module Parser
    def self.strip_nowiki_tag(s)
      s.gsub(%r{<nowiki>|</nowiki>}, "")
    end

    def self.strip_wiki_links(s)
      if s =~ /\[\[([^|]+)\]\]/ || s =~ /\[\[[^|]+\|([^|]+)\]\]/ || s =~ /\[\S+\s+([^|]+)\]/
        return $1
      end
      return s
    end
    
    # Implements parsing Ladle team templates
    module Teams
      # Parses the raw list of teams in wiki-text and returns a hash of teams and players.
      # 
      # Example:
      #   parse_ladle_players("{{LadleTeam|Team Blah|...}}") => {"Team Blah" => [...]}
      def parse_ladle_teams(raw_teams)
        teams = {}
        raw_teams.each_line do |line|
          line.chomp!
          if line =~ LadleTeamVersion1
            team, names = $1, $2
          elsif line =~ LadleTeamVersion2
            team, captain_name, captain_gid, names = $1, $2, $3, $4
          else
            next
          end
          names = split_names(names)
          names += split_names(captain_name) if captain_name
          teams[clean_name(team)] = names
        end
        teams
      end

      private

      def split_names(names)
        names = names.split(/\s*(?:,|;|(?!<)\/(?!nowiki))\s*/)
        names = names.reject { |name| name == "..." }
        names = names.map { |name| clean_name(name) }
        names
      end
      
      TemplateParameter = /(?:<nowiki>.*<\/nowiki>)|[^|]*/
      TemplateSep = /\s*\|\s*/
      Names = /(#{TemplateParameter})(?:#{TemplateSep}#{TemplateParameter})?/

      def self.make_ladle_team_regex(core)
        /^\s*\{{2}#{core}\}{2}/
      end

      # http://wiki.armagetronad.net/index.php?title=Template:Ladle_Team
      LadleTeamVersion1 = make_ladle_team_regex(
        /Ladle[ ]Team(?:[ ]External)?#{TemplateSep}
        (#{TemplateParameter})#{TemplateSep}
        #{Names}/x
      )

      # http://wiki.armagetronad.net/index.php?title=Template:LadleTeam
      LadleTeamVersion2 = make_ladle_team_regex(
        /LadleTeam(?:External)?#{TemplateSep}
        (#{TemplateParameter})#{TemplateSep}
        (#{TemplateParameter})#{TemplateSep}
        (#{TemplateParameter})#{TemplateSep}
        #{Names}/x
      )

      def clean_name(s)
        strip_nowiki_tag(s).strip
      end
    end
  
    # Implements parsing Ladle bracket results
    module Results
      BYE_NAME = /^(~bye.*|\s*)$/i

      # Parses the raw bracket in wiki-text and returns an array of results.
      # 
      # Example:
      #   parse_ladle_results("...") => [
      #     # Round 1
      #     [
      #       [["Team 1", 0], "Team 2", 2],
      #       [...]
      #     ],
      # 
      #     # Round 2
      #     [...]
      #   ]      
      def parse_ladle_results(raw_results)
        rounds = Hash.new { |h, k| h[k] = Round.new }        
        raw_results.each_line do |line|
          line.chomp!
          case line
          when /RD(\d+)-team0*(\d+)=(.*)/
            round, id = Integer($1), Integer($2)
            team = clean_score($3)
            if team =~ BYE_NAME
              team = nil
            end
            rounds[round].add_team(id, team)
          when /RD(\d+)-score0*(\d+)=(.*)/
            round, id = Integer($1), Integer($2)
            score = Integer(clean_score($3)) rescue nil
            rounds[round].add_score(id, score)
          end
        end
        sorted_rounds = rounds.to_a.sort_by { |(round_num, round)| round_num }
        return sorted_rounds.map { |(round_num, round)| round.to_a }
      end

      private
      
      # Represents a ladle round (semi-finals, finals...), where many bouts take place.
      class Round
        def initialize
          @scores = []
          @teams = []
        end
        
        def add_score(id, score)
          @scores << Score.new(id, score)
        end
        
        def add_team(id, name)
          @teams << Team.new(id, name)
          return nil
        end
        
        def to_a
          if (@scores.length % 2).nonzero?
            raise RuntimeError.new("Odd number of bouts. Something is messed up")
          end
          
          scores = @scores.sort_by { |score| score.id }
          round_results = []
          until scores.empty?
            score = scores.shift
            opponent_score = find_oppenent_score!(scores, score.id)
            round_results << [
              [find_team_name(score.id), score.score],
              [find_team_name(opponent_score.id), opponent_score.score]
            ]
          end
          return round_results
        end

        def remove_id(id)
          @scores.delete_if { |s| s.id == id }
          @teams.delete_if { |t| t.id == id }
        end
        
        private
        
        Team = Struct.new(:id, :name)
        Score = Struct.new(:id, :score)

        def find_oppenent_score(scores, id)
          scores.find { |other_score| other_score.id == self.class.opponent_id(id) }
        end

        def find_oppenent_score!(scores, id)
          s = find_oppenent_score(scores, id)
          scores.delete(s)
          s
        end

        def find_team_name(id)
          @teams.find { |t| t.id == id }.name
        end
                
        def self.opponent_id(n)
          if (n % 2).zero?
            return n - 1
          end
          return n + 1
        end
      end

      def clean_score(s)
        return strip_nowiki_tag(strip_wiki_links(s)).gsub(/'''/, "").strip
      end
    end
  end
end

module Ladle::Parser  
  extend Ladle::Parser::Teams
  extend Ladle::Parser::Results
end