def setUp(self): self.game = { '_id': '5983c19b9d043c3b77e57de0', 'game': 'game_x', 'kills': [{ 'player_dead': 'Isgalamido', 'player_killer': '<world>', 'type_gun': 'MOD_TRIGGER_HURT' }, { 'player_dead': 'Isgalamido', 'player_killer': '<world>', 'type_gun': 'MOD_TRIGGER_HURT' }, { 'player_dead': 'Isgalamido', 'player_killer': '<world>', 'type_gun': 'MOD_TRIGGER_HURT' }, { 'player_dead': 'Mocinha', 'player_killer': 'Isgalamido', 'type_gun': 'MOD_ROCKET_SPLASH' }, { 'player_dead': 'Isgalamido', 'player_killer': 'Isgalamido', 'type_gun': 'MOD_ROCKET_SPLASH' }] } self.player_deaths_by_world = Counter( get_players_deaths_by_world(self.game)) self.dict_kills = Counter(get_players_kills(self.game)) self.dict_kills.subtract(self.player_deaths_by_world) self.players = get_players(self.game)
def ensure_players_in_db(): existing = db.get_players() local_player_map = player_map.copy() for player in existing: if player.name in local_player_map: del local_player_map[player.name] if len(local_player_map) == 0: return # Get users list response = slack.slack_client.users.list() users = response.body['members'] user_map = {} for user in users: for name, grouping in local_player_map.items(): if user['profile']['real_name'].startswith( name) and not user['deleted']: user_map[name] = user['id'] db.add_player(user['id'], name, grouping) if len(user_map) != len(local_player_map): for key, value in user_map.items(): del local_player_map[key] print('Could not find slack ids for the following ', local_player_map)
def get_players_dictionary(): players = db.get_players() players_dictionary = dict() for player in players: players_dictionary[player.slack_id] = player.name return players_dictionary
def _view_game(game_id, init_path, game_edit_form=None, comment_form=None): """ Views existing game on given (comment) path. When there are errors with comment for instance of this one can be passed in and errors displayed. """ game = db.get_game(game_id) if not game: abort(404) # fetch games owner db.annotate(game) comments=list(db.get_comments_for_game(game_id)) for comment in comments: db.annotate(comment) # forms if not comment_form: comment_form = forms.CommentForm() user = db.get_user_by_username(session.get("username", None)) typeahead_players = [] if user and game.is_owner(user) and not game_edit_form: game_edit_form = forms.GameEditForm.form_factory(game.type)() # hint for inputting players names typeahead_players = dict([(player.name, player.rank) for player in db.get_players()]) print game.nodes return render_template("view_game.html", game=game, init_path=init_path, comments=comments, comment_paths=[(str(c["_id"]), c["path"]) for c in comments], comment_form=comment_form, typeahead_players=typeahead_players, game_edit_form=game_edit_form)
def connectionMade(self): self.logger.name = '<Connection %s:%s>' % (self.transport.getHost().host, self.transport.getHost().port) self.tries = 0 connections[self.transport] = None if options.args.auto_login: for p in db.get_players(): if p.uid == options.args.auto_login: self.logger.warning('Automatically authenticating as %s.', p.title()) self.sendLine('Automatically authenticating you as %s.' % p.title()) self.post_login(p) break else: self.logger.critical('Cannot find user %s in the database.', options.args.auto_login) self.sendLine('Sorry, autologin failed.', True) else: self.sendLine('Welcome to %s.' % get_config('server_name')) if options.args.max_connections and len(connections) > options.args.max_connections: self.sendLine('Sorry but the connection limit has been exceeded.', True) return self.logger.warning('Booting because connection limit exceeded.') elif db.players: self.get_username() else: self.sendLine('Creating initial user.') self.create_username() self.reset_timeout()
def scores(message): try: response = db.players_to_list(db.get_players()) bot.send_message(message.chat.id, response, parse_mode='Markdown') except Exception as e: print(e) bot.send_message(message.chat.id, 'Oh-oh, exception :(')
def print_group(self, channel, group): try: season = db.get_current_season() all_matches = db.get_matches_for_season(season) all_players = db.get_players() group_matches = [ m for m in all_matches if m.grouping.lower() == group.lower() ] if not len(group_matches): raise Exception('Not a match') players = gather_scores(group_matches) message = 'Group ' + group.upper() + ':' for p in players: message += '\n' + get_player_name( all_players, p['player_id']) + ' ' + str( p['m_w']) + '-' + str(p['m_l']) message += ' (' + str(p['s_w']) + '-' + str(p['s_l']) + ')' self.slack_client.api_call("chat.postMessage", channel=channel, text=message, as_user=True) except Exception as e: self.logger.debug(e) self.slack_client.api_call("chat.postMessage", channel=channel, text="Not a group (or I messed up).", as_user=True)
def get_player(player_id): conn, cursor = db.connect() players = db.get_players(cursor, ids=[player_id]) conn.close() if players: return players[0] raise PlayerDoesNotExist()
def test_add_match(players): slackbot.handle_command( "match <@{}> <@{}> nd 11 0".format(test_user_id, pingpongbot_id), test_user_id) conn, cursor = db.connect() matches = db.get_matches(cursor) p1 = db.get_players(cursor, [test_user_id])[0] p2 = db.get_players(cursor, [pingpongbot_id + "(nd)"])[0] conn.close() assert len(matches) == 1 assert matches[0].player1_score == 11 assert matches[0].player2_score == 0 assert matches[0].player2_id == pingpongbot_id + "(nd)" assert matches[0].player1_rating == 1000 assert p1.get_rating() == 1016 assert p2.get_rating() == 984
def update_display_name(player, new_name): conn, cursor = db.connect() players = db.get_players(cursor) names = [p.get_name().lower() for p in players] if new_name.lower() in names: return False db.update_player(cursor, player.get_id(), new_name=new_name) conn.commit() conn.close() return True
def test_undo(players): pingpong_service.add_match(test_user_id, False, pingpongbot_id, False, 11, 0) conn, cursor = db.connect() matches = db.get_matches(cursor) winner = db.get_players(cursor, ids=[test_user_id])[0] assert len(matches) == 1 assert winner.get_rating() == 1016 res = slackbot.handle_command("undo", test_user_id) assert res == responses.match_undone("erlend", 1000, "pingpong", 1000) players = db.get_players(cursor) conn.close() for p in players: assert p.get_rating() == 1000 assert pingpong_service.get_total_matches() == 0
def scores_to_all(message): try: global players response = db.players_to_list(db.get_players()) bot.send_message(message.chat.id, 'Sending the results.') for id in players: bot.send_message(id, response, parse_mode='Markdown') except Exception as e: print(e) bot.send_message(message.chat.id, 'Oba, exception :(')
def get_leaderboard(): conn, cursor = db.connect() players = db.get_players(cursor) matches = db.get_matches(cursor) active_players = [p for p in players if __has_played_match(matches, p)] printable_leaderboard = "\n".join([ "{}. {} ({})".format(i + 1, p.get_name(), p.get_rating()) for i, p in enumerate(active_players) ]) conn.close() return printable_leaderboard
def update_groupings(): ensure_players_in_db() existing = db.get_players() for name, grouping in player_map.items(): for e in existing: if e.name == name: db.update_grouping(e.slack_id, grouping) if grouping == '': db.set_active(e.slack_id, False) else: db.set_active(e.slack_id, True)
def print_whole_week(self, channel, date): all_weekly_matches = db.get_matches_for_week(date) players = db.get_players() message = "" for match in all_weekly_matches: message = message + f"\n {get_player_name(players, match.player_1_id)} vs. {get_player_name(players, match.player_2_id)} : week: {match.week}" self.slack_client.api_call("chat.postMessage", channel=channel, text=message, as_user=True)
def test_get_display_name(players): res = slackbot.handle_command("name emil", test_user_id) conn, cursor = db.connect() players = db.get_players(cursor, ids=[test_user_id, test_user_id + "(nd)"]) conn.close() p = players[0] p_nd = players[1] assert res == responses.name_updated("emil") assert p.get_id() == test_user_id assert p.get_name() == "emil" assert p_nd.get_name() == "emil(nd)"
def test_get_display_name_taken(players): res = slackbot.handle_command("name pingpong", test_user_id) conn, cursor = db.connect() players = db.get_players(cursor, ids=[test_user_id, test_user_id + "(nd)"]) conn.close() p = players[0] p_nd = players[1] assert res == responses.name_taken() assert p.get_id() == test_user_id assert p.get_name() == "erlend" assert p_nd.get_name() == "erlend(nd)"
def test_add_player(): slackbot.handle_command("hello", test_user_id) res = slackbot.handle_command("name erlend", test_user_id) conn, cursor = db.connect() players = db.get_players(cursor) conn.close() assert res == responses.name_updated("erlend") assert len(players) == 2 assert players[0].get_name() == "erlend" assert players[0].get_id() == test_user_id assert players[1].get_name() == "erlend(nd)" assert players[1].get_id() == test_user_id + "(nd)"
def print_user_week(self, user_id, channel, date): all_weekly_matches = db.get_matches_for_week(date) players = db.get_players() user_match_dict = dict() for match in all_weekly_matches: if match.player_1_id == user_id: user_match_dict[get_player_name( players, match.player_2_id)] = match.week elif match.player_2_id == user_id: user_match_dict[get_player_name( players, match.player_1_id)] = match.week message = "" for player, week in user_match_dict.items(): message = message + f"\n Playing: {player} | week: {week}" self.slack_client.api_call("chat.postMessage", channel=channel, text=message, as_user=True)
def get_player_stats(name): conn, cursor = db.connect() players = db.get_players(cursor) try: player = next(player for player in players if player.name == name) except StopIteration: raise PlayerDoesNotExist() wins = 0 losses = 0 matches = db.get_matches(cursor) for match in matches: if match.player1_id == player.id: if match.player1_score > match.player2_score: wins += 1 else: losses += 1 elif match.player2_id == player.id: if match.player2_score > match.player1_score: wins += 1 else: losses += 1 wl_ratio = "{:.2f}".format(wins / losses) if losses > 0 else '∞' return player.get_rating(), wins, losses, wl_ratio
def print_new_groups(): season = db.get_current_season() all_matches = db.get_matches_for_season(season) all_players = db.get_players() groups = sorted(list(set([m.grouping for m in all_matches]))) last_group_letter = '' last_group = [] last_relegated = [] last_relegated_2 = [] for group in groups: group_matches = [m for m in all_matches if m.grouping == group] players = match_making.gather_scores(group_matches) promoted = players[:2] player_names = [] if len(last_group): for player in last_group + promoted + last_relegated_2: name = [ p.name for p in all_players if p.slack_id == player['player_id'] ][0] print("u'" + name + "': '" + last_group_letter + "',") last_relegated_2 = last_relegated[:] last_relegated = players[-2:] last_group = players[2:len(players) - 2] last_group_letter = group player_names = [] for player in last_group + last_relegated_2: name = [ p.name for p in all_players if p.slack_id == player['player_id'] ][0] print("u'" + name + "': '" + last_group_letter + "',")
def match_player(text, players = None): """Match a list of players. players defaults to db.get_players().""" return match(text, players if players else db.get_players(), method = '__contains__')
def get_leaderboard(self, reverse_order=True): matches = db.get_matches() players = db.get_players() player_dict = dict() for player in players: player_dict[player.slack_id] = { 'games_won': 0, 'games_total': 0, 'name': player.name } for match in matches: games_played = match.sets player_1 = player_dict[match.player_1_id] player_2 = player_dict[match.player_2_id] player_dict[match.player_1_id][ 'games_total'] = player_1['games_total'] + games_played player_dict[match.player_2_id][ 'games_total'] = player_2['games_total'] + games_played if match.player_1_id == match.winner_id: player_dict[ match.player_1_id]['games_won'] = player_1['games_won'] + 2 if games_played == 3: player_dict[match.player_2_id][ 'games_won'] = player_2['games_won'] + 1 elif match.player_2_id == match.winner_id: player_dict[ match.player_2_id]['games_won'] = player_2['games_won'] + 2 if games_played == 3: player_dict[match.player_1_id][ 'games_won'] = player_1['games_won'] + 1 winrate_dict = dict() for player_id, player in player_dict.items(): if player['games_total'] == 0: winrate_dict[player['name']] = { 'games_won': 0, 'games_lost': 0, 'winrate': round(0, 2) } else: winrate_dict[player['name']] = { 'games_won': player['games_won'], 'games_lost': player['games_total'] - player['games_won'], 'winrate': round((player['games_won'] / player['games_total']) * 100, 2) } sorted_winrates = collections.OrderedDict( sorted(winrate_dict.items(), key=lambda x: x[1]['winrate'], reverse=reverse_order)) return sorted_winrates
def handle_line(self, line): """The threaded version of lineReceived.""" if self.state == FROZEN: self.sendLine('You are totally frozen.') self.logger.info('attempted command while frozen: %s', line) elif self.state == READY: commands.do_command(connections[self.transport], line) else: self.reset_timeout() if self.state == USERNAME: if line: if line == 'new': self.create_username() else: self.uid = line self.state = PASSWORD self.sendLine('Password: '******'You must provide a username.', True) elif self.state == PASSWORD: for p in db.players: if p.authenticate(self.uid, line): logger.info('Authenticated as %s.', p.title()) self.sendLine('Welcome back, {name}.{delimiter}{delimiter}You last logged in on {connect_time} from {connect_host}.'.format(name = p.title(), delimiter = self.delimiter.decode(options.args.default_encoding) if hasattr(self.delimiter, 'decode') else self.delimiter, connect_time = ctime(p.last_connected_time), connect_host = p.last_connected_host)) self.post_login(p) break else: self.logger.info('Failed to authenticate with username: %s.', self.uid) self.sendLine('Invalid username and password combination.', True) elif self.state == CREATE_USERNAME: self.tries += 1 if self.tries >= get_config('max_create_retries'): return self.sendLine(get_config('max_create_retries_exceeded'), True) if line: for p in db.players: if p.uid == line: self.sendLine('That username is already taken.') self.create_username() break else: self.uid = line self.tries = 0 self.create_password() else: self.sendLine('Usernames must not be blank.', True) elif self.state == CREATE_PASSWORD_1: self.tries += 1 if self.tries >= get_config('max_create_retries'): return self.sendLine(get_config('max_create_retries_exceeded'), True) if not line: self.sendLine('Passwords must not be blank.') self.create_password() else: self.sendLine('Retype password: '******'Passwords do not match.') self.create_password() elif self.state == CREATE_NAME: self.tries += 1 if self.tries >= get_config('max_create_retries'): return self.sendLine(get_config('max_create_retries_exceeded'), True) if line: line = line.title() for p in db.players: if p.name == line: self.sendLine('Sorry, but that name is already taken.') self.create_name() else: msg = util.disallowed_name(line) if msg: self.sendLine(msg) self.create_name() else: self.name = line self.tries = 0 self.create_gender() else: self.sendLine('You must choose a name.') self.create_name() elif self.state == CREATE_SEX: if line == '1': gender = genders.MALE elif line == '2': gender = genders.FEMALE else: self.sendLine('Invalid input: %s. Try again.' % line) return self.create_gender() self.sendLine('You are now a %s.' % gender.sex) p = objects.PlayerObject(self.name) p.gender = gender p.uid = self.uid p.pwd = self.pwd if len(list(db.get_players())) == 1: # This is the only player. p.access = objects.players.WIZARD for o in db.objects: o.owner = p self.logger.info('Created %s player: %s.', 'wizard' if p.access else 'normal', p.title()) p.move(db.objects_config['start_room']) self.post_login(p) elif self.state == READING: try: self.transport.read_func(line.decode(options.args.default_encoding) if hasattr(line, 'decode') else line) except Exception as e: self.sendLine('An error was raised while passing the line to the target function. See log for details.') self.logger.exception(e) finally: self.state = READY self.transport.read_func = None else: self.logger.warning('Unknown connection state: %s.', self.state) self.sendLine('Sorry, but an unknown error occurred. Please log in again.') if connections[self.transport]: connections[self.transport].transport = None connections[self.transport] = None self.get_username()
def test_get_players(self): self.assertEqual(len(get_players(self.game)), 2) self.assertEqual(get_players(self.game), ['Isgalamido', 'Mocinha'])
def print_season_markup(season=None): if season is None: season = db.get_current_season() all_matches = db.get_matches_for_season(season) all_players = db.get_players() groupings = list(set(map(lambda match: match.grouping, all_matches))) weeks = list(set(map(lambda match: match.week, all_matches))) groupings.sort() weeks.sort() output = '' ### ###||heading 1||heading 2||heading 3|| ###|cell A1|cell A2|cell A3| ###|cell B1|cell B2|cell B3| max_group_size = 0 for grouping in groupings: group_players = [p for p in all_players if p.grouping == grouping] if len(group_players) > max_group_size: max_group_size = len(group_players) standing_groups = [] # standing_groups.append(groupings) standing_groups.append(groupings[:6]) standing_groups.append(groupings[6:]) first_group = True for standing_group in standing_groups: if first_group: first_group = False output += 'h2. Standings\n' else: output += 'h2. Standings Cont.\n' for grouping in standing_group: output += '||Group ' + grouping output += '||\n' for i in range(0, max_group_size): output += '|' for grouping in standing_group: group_matches = [ m for m in all_matches if m.grouping == grouping ] players = gather_scores(group_matches) if len(players) > i: p = players[i] output += get_player_name( all_players, p['player_id']) + ' ' + str(p['m_w']) + '-' + str( p['m_l'] ) # + ' (' + str(p['s_w']) + '-' + str(p['s_l']) + ')' else: output += ' ' output += '|' output += '\n' for grouping in groupings: group_matches = [m for m in all_matches if m.grouping == grouping] output += '\nh2. Group ' + grouping + '\n' matches_by_week = {} for week in weeks: output += '||' + str(week) matches_by_week[week] = [ m for m in group_matches if m.week == week ] output += '||\n' for i in range(0, len(matches_by_week[weeks[0]])): for week in weeks: if i >= len(matches_by_week[week]): break m = matches_by_week[week][i] output += '|' + get_player_print( all_players, m.player_1_id, m) + '\\\\' + get_player_print( all_players, m.player_2_id, m) output += '|\n' return output
def players(): if request.method == 'POST': if not request.is_json: return jsonify({"msg": "Missing JSON in request"}), 400 return add_player(request.get_json()) return get_players()