How do I model teams and gameplay in this scorekeeping application?

Posted by Eric Hill on Stack Overflow See other posts from Stack Overflow or by Eric Hill
Published on 2010-06-16T00:24:56Z Indexed on 2010/06/16 0:32 UTC
Read the original article Hit count: 311

I'm writing a scorekeeping application for card game that has a few possibly-interesting constraints. The application accepts user registrations for players, then lets them check-in to a particular game (modeled as Event). After the final player registers, the app should generate teams, singles or doubles, depending on the preference of the person running the game and some validations (can't do doubles if there's an odd number checked in). There are @event.teams.count rounds in the game.

To sum up:

  • An event consists of `@event.teams.count` rounds;
  • Teams can have 1 or more players
  • Events have n or n/2 teams (depending on whether it's singles or doubles)
  • Users will be members of different teams at different events

Currently I have a rat's nest of associations:

class User < ActiveRecord::Base
  has_many :teams, :through => :players
  has_many :events, :through => :teams

class Event < ActiveRecord::Base
  has_many :rounds
  has_many :teams
  has_many :players, :through => :teams

class Player < ActiveRecord::Base
  belongs_to :user
  belongs_to :team
end

class Team < ActiveRecord::Base
  has_many :players
  belongs_to :event
end

class Round < ActiveRecord::Base
  belongs_to :event
  belongs_to :user
end

The sticky part is team generation. I have basically a "start game" button that should freeze the registrations and pair up teams either singly or doubly, and render to Round#new so that the first (and subsequent) matches can be scored. Currently I'm implementing this as a check on Round#new that calls Event#generate_teams and displays the view:

# Event#generate_teams
def generate_teams
  # User has_many :events, :through => :registrations
  # self.doubles is a boolean denoting 2 players per team
  registrations.in_groups_of(self.doubles ? 2 : 1, nil).each do |side|
    self.teams << Player.create(self,side)
  end
end

Which doesn't work. Should there maybe be a Game model that ties everything together rather than (my current method) defining the game as an abstraction via the relationships between Events, Users, and Rounds (and Teams and Players and etc.)? My head is swimming.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about data-structures