示例#1
0
文件: game.py 项目: acm-uiuc/mm20
    def add_new_team(self, data, client_id):
        response = {"status": "Success", "errors": []}
        try:
            if len(data["members"]) > self.team_limit:
                return (False, {"status": "Failure", "errors": [
                    "Number of team members exceeds team size"]})
            start_room = random.choice(self.rooms.values())
            try_limit = 1000
            while(try_limit > 0 and not start_room.canAdd(len(data["members"]))):
                start_room = self.rooms[random.choice(self.rooms.keys())]
                try_limit = try_limit-1
            newTeam = Team(data["team"], data["members"],
                           start_room, self.people, client_id, self.turn_limit / 24)
        except KeyError as e:
            return (False, {"status": "Failure", "errors": [{"KeyError": e.message}]})
            
        # TODO: Make all error objects uniform
        self.result_buffer[client_id] = []
        self.teams[client_id] = newTeam
        response = {
            "status": "Success", 
            "team": newTeam.get_team_members(),
            "team_id": newTeam.my_id,
            "team_name": newTeam.name,
            "map": self.teams[client_id].get_visible_map(),
            "turns_per_hour": self.turn_limit / 24
        }

        return (True, response)
示例#2
0
def setup_game():
    # create board
    board = Board()
    # create teams
    white = Team('white')
    black = Team('black')
    teams = (white, black)
    # create pieces
    white_pawns = [Piece(white, 'pawn', number_to_letter(i)+str(2), 'p') for i in range(1, 9)]
    black_pawns = [Piece(black, 'pawn', number_to_letter(i)+str(7), 'P') for i in range(1, 9)]
    white_rooks = [Piece(white, 'rook', number_to_letter(i)+str(1), 'r') for i in range(1, 9, 7)]
    black_rooks = [Piece(black, 'rook', number_to_letter(i)+str(8), 'R') for i in range(1, 9, 7)]
    white_knights = [Piece(white, 'knight', number_to_letter(i)+str(1), 'n') for i in range(2, 8, 5)]
    black_knights = [Piece(black, 'knight', number_to_letter(i)+str(8), 'N') for i in range(2, 8, 5)]
    white_bishops = [Piece(white, 'bishop', number_to_letter(i)+str(1), 'b') for i in range(3, 7, 3)]
    black_bishops = [Piece(black, 'bishop', number_to_letter(i)+str(8), 'B') for i in range(3, 7, 3)]
    white_queen = [Piece(white, 'queen', 'd1', 'q')]
    black_queen = [Piece(black, 'queen', 'd8', 'Q')]
    white_king = [Piece(white, 'king', 'e1', 'k')]
    black_king = [Piece(black, 'king', 'e8', 'K')]
    white_pieces = [white_pawns, white_rooks, white_knights, white_bishops, white_queen, white_king]
    black_pieces = [black_pawns, black_rooks, black_knights, black_bishops, black_queen, black_king]
    # initialize teams
    white.initialize(white_pieces)
    black.initialize(black_pieces)
    # initialize board
    board.initialize((white_pieces, black_pieces))

    return board, teams
示例#3
0
def build_fixtures():
    cache_dir = __file__.replace("loader.py", "cache")

    obj_map = {
        "division": list(Division()),
        "position": list(Position()),
        "category": list(Category()),
        "team": list(Team()),
        "record": list(Record()),
        "profile": list(Profile()),
        "color": list(Color()),
        "teamnav": list(TeamNav()),
        "player": list(Player()),
        "playernav": list(PlayerNav()),
        "stat": list(Stat()),
        "teamstat": list(TeamStat()),
        "oppstat": list(OppStat()),
        "playerstat": list(PlayerStat())
    }

    fixture_dir = f"{cache_dir}/fixtures"
    os.makedirs(fixture_dir, exist_ok=True)

    fixtures = []
    for key, value in obj_map.items():
        filename = f"{fixture_dir}/{key}.json"
        with open(filename, "w") as f:
            json.dump(value, f)
        fixtures += value

    with open(f"{fixture_dir}/all.json", "w") as f:
        json.dump(fixtures, f)
示例#4
0
 def get(self):
   check_admin(self)
   games=Game.all().run()
   for g in games:
     g.delete()
   days=[26,27,28,28,29,30]
   for i in range(1,6):
     g=Game(round=i,date=date(2012,12,days[i]))
     g.put()
   us=Utilities.all().run()
   for u in us:
     u.delete()
   u=Utilities()
   u.current_round=1
   u.next_game=Game.all().filter('round =',1).get()
   u.put()
   teams=Team.all().run()
   for t in teams:
     t.delete()
   games=PlayerGame.all().run()
   for g in games:
     g.delete()
   self.response.out.write('done')
   player=Player(first_name="any",surname="player",active=False)
   player.put()
示例#5
0
def get_team(user_meta=None,game=None):
  if not user_meta:
    user_meta=get_meta()
  if not game:
    game=next_game()
  if not game:
    game=Game.all().filter('round =',current_round()-1)
  return Team.all().filter('user ='******'game =',game).get()
示例#6
0
    def __init__(self):
        self.playernavs = []

        nfl_json = get_nfl_json()

        positions = Position()
        teams = Team()

        players = []

        for team_json in nfl_json.values():
            team_json = team_json.get("roster")
            team_json = team_json.get("page").get("content")
            team_json = team_json.get("roster")

            _player_team = team_json.get("team").get("uid")
            player_team = teams.find(_player_team)

            groups = team_json.get("groups")
            for group in groups:
                athletes = group.get("athletes")
                for athlete in athletes:
                    playernav_home = athlete.get("href")
                    playernav_headshot = athlete.get("headshot")
                    playernav = (playernav_home, playernav_headshot)
                    self.playernavs.append(playernav)

                    player_uid = athlete.get("uid")
                    player_guid = athlete.get("guid")
                    player_name = athlete.get("name")

                    if "nophoto" in playernav_headshot:
                        player_headshot = "/static/app/nophoto.jpg"
                    else:
                        player_headshot = f"/static/app/headshots/{player_guid}.png"

                    _player_position = athlete.get("position")
                    player_position = positions.find(_player_position)

                    players.append((player_uid, player_guid, player_headshot,
                                    player_name, player_position, player_team))

        self.values = tuple(players)
        self.keys = ("uid", "guid", "headshot", "name", "position", "team")
        self.model = "app.player"
        self.key = "guid"
示例#7
0
 def get(self):
   user=get_meta()
   if not user:
     self.redirect("/")
   team=Team.all().filter("user ="******"/team/edit")
   players=Player.all().filter("active =",True).fetch(100)
   template_values={'user_meta':user,'players':players,'budget':user.budget}
   template=jinja_environment.get_template('templates/select_team.html')
   self.response.out.write(template.render(template_values))
示例#8
0
  def post(self):
    if self.request.get('code')!='RESET':
      return self.response.out.write("Reset failed. No harm done")
    check_admin(self)
    players=Player.all().run()
    for p in players:
      p.batting_price=p.initial_batting_price
      p.bowling_price=p.initial_bowling_price
      p.fielding_price=p.initial_fielding_price
      p.put()
		
    usermetas=UserMeta.all().run()
    for u in usermetas:
      u.total_trades=10
      u.round_trades=2
      u.total_points=0
      u.put()
    
    teams=Team.all().run()
    for t in teams:
      if t.game.round > 1:
        t.delete()
      else:
        t.batting_score=0
        t.bowling_score=0
        t.fielding_score=0
        t.total_score=0
        t.put()
        
    playergames=PlayerGame.all().run()
    for p in playergames:
      p.delete()
      
    games=Game.all().run()
    for g in games:
      g.played=False
      g.result='tie'
      g.score="0/0"
      g.opposition_score="0/0"
      g.batExtras=0
      g.bowlExtras=0
      g.put()
      
    u=Utilities.all().get()
    u.current_round=1
    u.next_game=Game.all().filter('round =',1).get()
    u.lockout=False
    u.put()
    
    memcache.flush_all()
    self.response.out.write('System reset. I hope you meant to do that!');
示例#9
0
    def add_new_team(self, data, client_id):
        response = {"status": "Success", "errors": []}
        try:
            if len(data["members"]) > self.team_limit:
                return (False, {
                    "status": "Failure",
                    "errors": ["Number of team members exceeds team size"]
                })
            start_room = random.choice(self.rooms.values())
            try_limit = 1000
            while (try_limit > 0
                   and not start_room.canAdd(len(data["members"]))):
                start_room = self.rooms[random.choice(self.rooms.keys())]
                try_limit = try_limit - 1
            newTeam = Team(data["team"], data["members"], start_room,
                           self.people, client_id, self.turn_limit / 24)
        except KeyError as e:
            return (False, {
                "status": "Failure",
                "errors": [{
                    "KeyError": e.message
                }]
            })

        # TODO: Make all error objects uniform
        self.result_buffer[client_id] = []
        self.teams[client_id] = newTeam
        response = {
            "status": "Success",
            "team": newTeam.get_team_members(),
            "team_id": newTeam.my_id,
            "team_name": newTeam.name,
            "map": self.teams[client_id].get_visible_map(),
            "turns_per_hour": self.turn_limit / 24
        }

        return (True, response)
示例#10
0
 def get(self):
   check_admin(self)
   us=UserMeta.all().run()
   for u in us:
     budget=209000
     team=Team.all().filter('user =',u).get()
     if team:
       for k in team.batsmen:
         p=db.get(k)
         budget -= p.batting_price
       for k in team.bowlers:
         p=db.get(k)
         budget -= p.bowling_price
       for k in team.fielders:
         p=db.get(k)
         budget -= p.fielding_price
       u.budget = budget
       save_user(u)
示例#11
0
 def __init__(self):
     teams = Team()
     self.values = tuple(teams.colors)
     self.keys = ("main", "alt")
     self.model = "app.color"
示例#12
0
 def __init__(self):
     teams = Team()
     self.values = tuple(teams.profiles)
     self.keys = ("abbr", "location", "name", "fullname", "divrank")
     self.model = "app.profile"
示例#13
0
 def __init__(self):
     teams = Team()
     self.values = tuple(teams.teamnavs)
     self.keys = ("home", "stats", "schedule", "roster", "depthchart",
                  "injuries", "transactions", "blog", "logo")
     self.model = "app.teamnav"
示例#14
0
    def __init__(self):
        self.oppstats = []

        nfl_json = get_nfl_json()

        stats = Stat()
        teams = Team()

        teamstats = []

        for team_json in nfl_json.values():
            team_json = team_json.get("stats")
            team_json = team_json.get("page").get("content")
            team_json = team_json.get("stats")

            _ts_team = team_json.get("team").get("uid")
            ts_team = teams.find(_ts_team)

            for ts_json in team_json.get("teamStats").get("team"):
                for ts_stat_json in ts_json.get("stats"):

                    _ts_stat = ts_stat_json.get("name")

                    if _ts_stat is not None:
                        ts_stat = stats.find(_ts_stat)

                        (ts_value, ts_string) = stats._eval_stat(ts_stat_json)

                        teamstat = (ts_value, ts_string, ts_stat, ts_team)
                        teamstats.append(teamstat)
                    else:
                        for ts_substat_json in ts_stat_json.get("stats"):

                            _ts_stat = ts_substat_json.get("name")
                            ts_stat = stats.find(_ts_stat)

                            (ts_value,
                             ts_string) = stats._eval_stat(ts_substat_json)

                            teamstat = (ts_value, ts_string, ts_stat, ts_team)
                            teamstats.append(teamstat)

            for os_json in team_json.get("teamStats").get("opponent"):
                for os_stat_json in os_json.get("stats"):

                    _os_stat = os_stat_json.get("name")

                    if _os_stat is not None:

                        (os_value, os_string) = stats._eval_stat(os_stat_json)

                        oppstat = (os_value, os_string)
                        self.oppstats.append(oppstat)
                    else:
                        for os_substat_json in os_stat_json.get("stats"):

                            (os_value,
                             os_string) = stats._eval_stat(os_substat_json)

                            oppstat = (os_value, os_string)
                            self.oppstats.append(oppstat)

        self.values = tuple(teamstats)
        self.keys = ("value", "string", "stat", "team")
        self.model = "app.teamstat"
示例#15
0
 def post(self):
   user_meta=get_meta()
   if not user_meta:
     self.redirect("/")
   team=Team.all().filter('user ='******'batting')
   selected_bowlers=self.request.get_all('bowling')
   selected_fieldsmen=self.request.get_all('fielding')
   
   if len(selected_batsmen) > 5 or len(selected_bowlers) > 3 or len(selected_fieldsmen) > 3:
     self.response.out.write("Error: too many selected")
     return
   
   if not self.request.get('captain'):
     self.response.out.write("Error: no captain selected")
     return
     
   captain=self.request.get('captain').split(':',1)
   if captain[0] not in ['bat','bowl','field']:
     self.response.out.write("Error: invalid captain selection")
     return
   if captain[0] == 'bat' and captain[1] not in selected_batsmen:
     self.response.out.write("Error: captain must be a member of team")
     return
   if captain[0] == 'bowl' and captain[1] not in selected_bowlers:
     self.response.out.write("Error: captain must be a member of team")
     return
   if captain[0] == 'field' and captain[1] not in selected_fieldsmen:
     self.response.out.write("Error: captain must be a member of team")
     return
   team.captain_type=db.Category(captain[0])
   team.captain=db.get(captain[1])
   
   for key in selected_batsmen:
     player=db.get(key)
     budget-=player.batting_price
     team.batsmen.append(player.key())
   
   for key in selected_bowlers:
     player=db.get(key)
     budget-=player.bowling_price
     team.bowlers.append(player.key())
     
   for key in selected_fieldsmen:
     player=db.get(key)
     budget-=player.fielding_price
     team.fielders.append(player.key())
     
   if budget < 0:
     self.response.out.write("You went over budget")
     return
     
   #if team.game.round > 1:
   #  team1=Team(user=team.user,game=Game.all().filter('round =',1).get(),batsmen=team.batsmen,bowlers=team.bowlers,fielders=team.fielders,captain=team.captain,captain_type=team.captain_type)
   #  team1.put()
     
   team.put()
   user_meta.budget = budget
   save_user(user_meta)
   
   self.redirect('/team')