summaryrefslogtreecommitdiff
path: root/lib/scheduling/round_robin.rb
blob: 7ee617d030f4a28a1d8b711781a481418d3e8798 (plain)
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
# http://stackoverflow.com/questions/6648512/scheduling-algorithm-for-a-round-robin-tournament
module Scheduling
	class RoundRobin
		include Rails.application.routes.url_helpers

		def initialize(tournament_stage)
			@tournament_stage = tournament_stage
		end

		def create_matches
			# => find the number of matches and teams to create
			@num_teams = (tournament.players.count/tournament.min_players_per_team).floor
			@matches_per_round = (@num_teams / tournament.min_teams_per_match).floor

			# => initialize data and status members
			@team_pairs ||= Array.new
			if @team_pairs.empty?
				@matches_finished = 0
			end

			# => Create new matches
			@matches_per_round.times do
				tournament_stage.matches.create
			end

			# => seed the first time
			if @team_pairs.empty?
				tournament_stage.seeding.seed(tournament_stage)
				tournament_stage.matches.each {|match| match.teams.each {|team| @team_pairs.push team}}
			else
				# => Reorder the list of teams
				top = @team_pairs.shift
				@team_pairs.push @team_pairs.shift
				@team_pairs.unshift top

				# => Add the teams to the matches
				match = tournament_stage.matches[@matches_finished-1]
				matches = 1
				(0..@team_pairs.count-1).each do |i|
					match.teams += @team_pairs[i]
					if @team_pairs.count.%(tournament.min_teams_per_match).zero?
						match = tournament_stage.matches[@matches_finished-1 + matches]
						matches += 1
					end
				end

			end

			# => Set the match statuses to ready (1)
			tournament_stage.matches.each {|match| match.update(status: 1)}

		end

		def finish_match(match)
			@matches_finished += 1
		end

		def graph(current_user)
		end

		private
		def tournament_stage
			@tournament_stage
		end

		def tournament
			tournament_stage.tournament
		end
	end
end