def get_player_stats(year, week): games = nflgame.games(year, week) players = nflgame.combine_max_stats(games) for player in players: fantasy_points = (player.passing_yds * .04 + player.passing_tds * 4 - player.passing_int + player.rushing_yds * .1 + player.rushing_tds * 6 + player.receiving_yds * .1 + player.kickret_tds * 6 + player.receiving_tds * 6 + (player.receiving_twoptm + player.rushing_twoptm + player.passing_twoptm) * 2 - player.fumbles_lost * 2 + player.fumbles_rec_tds * 6) two_point_conversions = player.receiving_twoptm + player.rushing_twoptm + player.passing_twoptm # try: p = Player(player.name, year, week, player.player.position, fantasy_points, player.passing_yds, player.passing_tds, player.passing_int, player.rushing_yds, player.rushing_tds, player.receiving_yds, player.receiving_tds, player.kickret_tds, two_point_conversions, player.fumbles_lost, player.fumbles_rec_tds) except AttributeError: p = Player(player.name, year, week, "N/A", fantasy_points, player.passing_yds, player.passing_tds, player.passing_int, player.rushing_yds, player.rushing_tds, player.receiving_yds, player.receiving_tds, player.kickret_tds, two_point_conversions, player.fumbles_lost, player.fumbles_rec_tds) db.session.add(p) db.session.commit()
def populate_player_table(players, session): id = 0 for player in players: attributes = { 'first': player['first_name'], 'last': player['last_name'], 'atp_url': player['player_url'], 'country': player['flag_code'], 'date_of_birth': player['birth_date'], 'turned_pro': player['turned_pro'], 'weight_lbs': player['weight_lbs'], 'weight_kg': player['weight_kg'], 'height_inches': player['height_inches'], 'height_cm': player['height_cm'] } try: attributes['handedness'] = player['handedness'][0:1] except: attributes['handedness'] = None try: attributes['backhand'] = player['backhand'][0:1] except: attributes['backhand'] = None session.add(Player(**attributes)) id += 1
def connection(message): print "Connection: ", message['data'], request.sid if message['data']['type'] == 'player': if 'playerId' in message['data']: player = Player.get_by_id(message['data']['playerId']) print "Player", player.name, "reconnected" print "Updating player sid to:", request.sid player.update_sid(request.sid) emit('connection', {'data': { 'objectives complete': player.objectives_complete }}) else: name = message['data']['name'] # Use actual game code when implemented # game = Game.get_by_key(message['data']['game key']) player = game1.add_player(name, request.sid) emit('connection', {'data': {'id': player.id}}) # DEBUG print "Current players: " for p in game1.player_list(): print p.name, print
def bet(): bets = json.loads(request.json) # bet_type: amount key values rnd = Rounds.current_by_room_id(g.player.room_id) if rnd is None: return json.dumps({'status': 3}) Bets.insert_bets(bets, g.player.id, rnd.id, Player.are_bets_real()) return json.dumps({'status': 1})
def disconnect(): player = Player.get_by_id(request.sid) if player: print player.name, "disconnected.", request.sid if player.active: game = Game.get_by_key(player.game_key) print "Deactivating player" game.deactivate_player(player) else: print "Someone disconnected", request.sid
def rank(): player = Player.get_by_id(request.sid) print player.name, "requested its rank." game = Game.get_by_key(player.game_key) rank = game.get_player_rank(player) emit('rank', {'data': { 'rank': rank, 'num players': len(game.player_list()) }})
def create_player(row, names, info): db.session.add( Player(first=names[row].select("span.name-col__firstName")[0].text, last=names[row].select("span.name-col__lastName")[0].text, special=names[row].select( "span.name-col__special")[0].text.strip(), number=info[row].select("td.number-col")[0].text, position=info[row].select("td.position-col")[0].text, shoots=info[row].select("td.shoots-col")[0].text, height=info[row].select("td.height-col > span.xs-sm-md-only") [0].text, weight=info[row].select("td.weight-col")[0].text)) return player
def handle_message(self, message, ip_address): '''Handles message received from a client thread''' message = message.decode() session = Session() try: message = message.split(";") message = [datapair.split(":") for datapair in message] message = [[value.strip() for value in sublist] for sublist in message] data = {str(sublist[0]): str(sublist[1]) for sublist in message} if "msgtype" in data: if data["msgtype"] == "connect": player = session.query(Player).filter_by( username=data["alias"]).first() if not player: player = Player(username=data["alias"], ip=ip_address) session.add(player) session.commit() logging.info("Connect type msg received from %s", ip_address) return "connect type msg received" if data["msgtype"] == "play": round_answers.append((data["alias"], data["answer"])) logging.info("play type msg received from %s", ip_address) return "play type msg" except KeyError: print("Missing fields in clients message", flush=True) logging.exception("KeyError in RPSGame for ip %s", ip_address) except IndexError as e: print(e, flush=True) logging.exception("IndexError in RPSGame for ip %s", ip_address) return "Wrong message fields" except IntegrityError: print("integrityerror in db") logging.exception("IntegrityError RPSGame for ip %s", ip_address) except Exception as e: print(" error", flush=True) print(e, flush=True) logging.exception("Exception in RPSGame for ip %s", ip_address) return "error in msg"
def rank(message): player = Player.get_by_id(request.sid) print player.name, "completed an objective: ", message game = Game.get_by_key(player.game_key) print "game:", game.name objective = Objective.get_by_id(message['data']['objectiveId']) print "completing: ", objective.name if player.id in objective.players_completed: print "Player ", player.name, "is trying to complete objective", objective.name, "twice!" return time = message['data']['time'] pic_url = message['data']['url'] game.player_complete_objective(player, objective, time, pic_url) print "Process completed objective"
def run(): try: os.remove('app.log') except: pass logging.config.fileConfig('logger.conf') logger = logging.getLogger("app") logger.info("Program started") sys_argv = sys.argv sys_argv += ['--style', 'universal'] app = QApplication(sys_argv) player = Player() app.exec_() logger.info("exit") sys.exit()
def game_stats(): print "Getting game stats" try: data = json.loads(request.data) print data game_id = data['game_id'] game = Game.get_by_key(game_id) objective_stats = [] for objective in game.objective_list(): players_complete = [{ 'id': player_id, 'name': Player.get_by_id(player_id).name } for player_id in objective.players_completed] objective_stats.append({ 'id': objective.id, 'name': objective.name, 'players_complete': players_complete }) player_stats = [] for player in game.player_list(): player_info = player.serialize() player_info['rank'] = game.get_player_rank(player) player_stats.append(player_info) return jsonify({ 'data': { 'objective_stats': objective_stats, 'player_stats': player_stats }, 'status': 200 }) except: return getErrorJson(sys.exc_info())
def game(): room_id = Player.join_some_room() balance = Player.get_balance() return render_template('game.html', room_id=room_id, balance=balance)
def _get_player1(): return Player(name="John", team="Bears")
def _get_player(color="red"): return Player(color="red")
def _get_player2(): return Player(name="Bill", team="Wolves")
def _get_player3(): return Player( name="Mary", team="Beavers" #this team doesn´t exist )
import unittest.mock as mock from unittest.mock import patch import os import sys sys.path.append(os.path.abspath('../../')) from app import Player, order_by_name, order_by_score, check_user_exists DATABASE = 'database' EXPECTED = 'expected' USERNAME = '******' WINNER = 'winner' LOSER = 'loser' # Player records p1 = Player(username='******', score=340) p2 = Player(username='******', score=150) p3 = Player(username='******', score=175) p4 = Player(username='******', score=400) p5 = Player(username='******', score=200) p6 = Player(username='******', score=300) class OrderLeaderBoardByNameTest(unittest.TestCase): ''' Verify that the database returns results ordered alphabetically by username ''' def setUp(self): self.test_cases = [ { DATABASE: [p5,p3,p2], EXPECTED: [['Bill',150],['Harold',175],['Zeke',200]] },
def get_token(): if not Player.is_logged_in(): return json.dumps({'status': 2}) return json.dumps({'status': 1, 'token': Player.get_token()})
def update_stats(): teamids = [] with app.app_context(): query = db.session.query(Team.teamid.distinct().label("teamid")) for item in query: teamid = str(item)[1:] teamid = teamid[:-2] teamids.append(teamid) for tid in teamids: current_season = sbteamdata.get_current_season() team = Team.query.filter_by(teamid=tid, season=current_season).first() if team and (team.time - datetime.now()).total_seconds() > -600: players = Player.query.filter_by(teamid=tid, season=current_season).all() pitchers = Pitcher.query.filter_by( teamid=tid, season=current_season).all() else: stats = sbteamdata.get_team_data(tid) team = Team.query.filter_by(teamid=tid).order_by( Team.season.desc()).all() players = Player.query.filter_by(teamid=tid, season=stats.season).all() pitchers = Pitcher.query.filter_by(teamid=tid, season=stats.season).all() for entry in team: if entry.season == int(stats.season): db.session.delete(entry) db.session.commit() new_entry = Team(datetime.now(), stats.season, tid, stats.name, stats.stars, stats.stadium, stats.pl, stats.pl_position, stats.trained, stats.games, stats.ab, stats.hits, stats.avg, stats.singles, stats.doubles, stats.triples, stats.hr, stats.rbi, stats.so, stats.era, stats.slg, stats.wins, stats.losses, stats.pct, stats.rs, stats.ra) db.session.add(new_entry) if players: for player in players: db.session.delete(player) db.session.commit() for player in stats.players: new_entry = Player(stats.season, tid, player.id, player.name, player.position, player.games, player.ab, player.hits, player.avg, player.singles, player.doubles, player.triples, player.hr, player.rbi, player.so, player.era, player.slg) db.session.add(new_entry) if pitchers: for player in pitchers: db.session.delete(player) db.session.commit() for player in stats.pitchers: new_entry = Pitcher(stats.season, tid, player.id, player.name, player.games, player.so, player.era) db.session.add(new_entry) db.session.commit()
def error(message): print pcol.bold(pcol.red(message)) exit(1) def query(question): return raw_input(pcol.bold(pcol.yellow(question))) info("Welcome to SlackJack!") name = query("What's your name?") play = True while play: bet = query("How much would you like to bet?") if not bet.isdigit(): error("{} is an invalid bet amount.".format(bet)) player = Player(name, bet, info) game = Game.create([player]) while not game.can_make_move(player): sleep(0.1) while game.can_make_move(player): move_raw = query("What would you like to do? [H = Hit, S = Stand]") move = Move.from_raw(move_raw, player, game) Game.move(move) play = str(query("Play again? [Y/N]")).lower() == 'y'
stats.singles, stats.doubles, stats.triples, stats.hr, stats.rbi, stats.so, stats.era, stats.slg, stats.wins, stats.losses, stats.pct, stats.rs, stats.ra) db.session.add(new_entry) if players: for player in players: db.session.delete(player) db.session.commit() for player in stats.players: new_entry = Player(stats.season, tid, player.id, player.name, player.position, player.games, player.ab, player.hits, player.avg, player.singles, player.doubles, player.triples, player.hr, player.rbi, player.so, player.era, player.slg) db.session.add(new_entry) if pitchers: for player in pitchers: db.session.delete(player) db.session.commit() for player in stats.pitchers: new_entry = Pitcher(stats.season, tid, player.id, player.name, player.games, player.so, player.era) db.session.add(new_entry) db.session.commit()