Example #1
0
def savePlayers():
    qo = Player().queryObject()
    for p in qo.all():
        RVEngine.log("Updating " + str(p.varname))
        p.update()

    return True
Example #2
0
def savePlayers():
	qo = Player().queryObject()
	for p in qo.all():
		RVEngine.log("Updating " + str(p.varname))
		p.update()

	return True
Example #3
0
def add_player():
    form = PlayerForm()
    if form.validate_on_submit():
        player = Player()
        player.team_id = form.add_team.data.id
        db.session.add(player)
        form.populate_obj(player)
        db.session.commit()
        flash("Added player")
        return redirect(url_for("index"))
    return render_template("errors.html", form = form)
Example #4
0
def create_test_room():
    players = [
        Player('alan', '12354', 'mafia', 'alive', False),
        Player('noob1', '42314', 'civilian', 'alive', False),
        Player('noob2', '22222', 'civilian', 'alive', False),
        Player('noob3', '33333', 'civilian', 'alive', False),
        Player('noob4', '44444', 'civilian', 'alive', False)
    ]
    targets = Targets('', '', '')
    gameMessages = [Message('Pre-Game', 'Waiting for players...')]
    observerMessages = [
        Message('Pre-Game', 'Waiting for players...'),
        Message('Observer Message', 'Testing...')
    ]
    room = Room('0001', 2, 0, players, targets, 'pre-game', 'pre-game', True,
                '55555', [], gameMessages, observerMessages)
    database.append(room)

    LOG.info('Test room created..')
Example #5
0
def loadPlayer(netid, uid, varname):
	RVEngine.log("Loading Player from uid " + uid)
	qo = Player().queryObject()
	p = qo.filter(Player.uid == uid).first()
	RVEngine.log("Passed filter")
	if p is None:
		RVEngine.log("Player not found, creating.")
		p = Player()
		p.uid = uid
		p.varname = varname
		p.save()
	RVEngine.log("Passed is None, got " + str(p.varname))
	p.netid = netid
	p.sync = True
	RVEngine.log("Updating player")
	# p.update()
	RVEngine.log("Loading unitdata")
	RVEngine.loadPlayer(p)
	return p
Example #6
0
def name(redir=None):
    if request.method == 'POST':
        # Redirect to previous page after setting name
        # TODO: Check for security flaws with this technique
        response = None
        if redir:
            response = make_response(redirect(f'/{redir}'))
        else:
            response = make_response(
                render_template('name.html', error=None, redir=redir))

        # Validate that the user accepted the use of cookies
        if not request.cookies.get('cookies'):
            return render_template(
                'name.html',
                error='You must accept the use of cookies before proceeding.',
                redir=redir)

        # Validate recaptcha
        if not recaptcha.verify():
            return render_template('name.html',
                                   error='ReCaptcha failed.',
                                   redir=redir)

        # Get and valiate chosen name
        name = request.form.get('name')
        name_validation, name_error = validation.validate_name(name)
        if not name_validation:
            return render_template('name.html', error=name_error, redir=redir)

        player_id = request.cookies.get('uuid')
        player = Player.query.filter_by(uuid=player_id).first()

        # If player already exists, just change the name
        if player_id and player:
            player.name = name
        else:
            player: Player = Player(name)
            db.session.add(player)
            response.set_cookie('uuid', player.uuid)

        db.session.commit()

        return response

    else:
        return render_template('name.html', error=None, redir=redir)
Example #7
0
def newPlayer(club_id):
    if 'username' not in login_session:
        return redirect('/login')
    if request.method == 'POST':
        newPlayer = Player(name=request.form['name'],
                           description=request.form['description'],
                           jersey=request.form['jersey'],
                           position=request.form['position'],
                           club_id=club_id,
                           user_id=login_session['user_id'])
        session.add(newPlayer)
        flash('Player Successfully Signed')
        session.commit()

        return redirect(url_for('showPlayer', club_id=club_id))
    else:
        return render_template('newplayer.html', club_id=club_id)
Example #8
0
def playerStat():

    if request.method == 'POST':

        id = request.form.get('player_id')
        team_id = request.form.get('team_id')
        sc_runs = request.form.get('runs_scored')
        pl_balls = request.form.get('balls_faced')
        gv_runs = request.form.get('runs_given')
        th_balls = request.form.get('balls_thrown')
        wickets = request.form.get('wickets')

        player = Player(id=id, team_id=team_id, sc_runs=sc_runs, pl_balls=pl_balls, gv_runs=gv_runs, th_balls=th_balls, wickets=wickets)

        db.updateStats(player)

        return redirect(url_for('dashboard'))

    return render_template("./admin/playerStat.html", title="Stats")
Example #9
0
def add_random_player():
    form = PlayerForm()
    helloJson = request()
    player = Player()
    player.name = helloJson['name']
    player.birthdate = helloJson['birth_data']
    player.height = helloJson['height']
    player.weight = helloJson['weight'] 
    becauseDebugging = random.randint(1,Team.query.count())
    player.team_id = becauseDebugging
    db.session.add(player)
    db.session.commit()
    flash("Random player " + player.name + " was born on " + player.birthdate )
    return redirect(url_for("index"))
Example #10
0
def join_room():
    LOG.info(request.access_route[0] + ' requested ' + request.url)
    if request.method == 'OPTIONS':
        return build_preflight_response()
    elif request.method == 'POST':
        userId = request.cookies.get('userId')
        roomId = request.form.get('roomId')
        join_option = request.form.get('option')
        print(join_option)
        if join_option == 'observe':
            return build_actual_response({"message": "Observer connection"},
                                         200,
                                         setCookie=True,
                                         cookie='observer')

        isValidRoom = False
        room = None
        new_player = Player(request.form.get('name'),
                            uuid.uuid4().hex, 'unassigned', 'alive', False)

        for i in database:
            if i.id == roomId:
                isValidRoom = True
                room = i

        if isValidRoom:
            if room.status != 'pre-game':
                return build_actual_response(
                    {"message": "Observer connection"}, 200)
            for i in room.players:
                if i.userId == userId:
                    return build_actual_response(
                        {"message": "Player reconnected"}, 200)
            room.players.append(new_player)
        else:
            return build_actual_response({"message": "Not Found"}, 404)
        return build_actual_response({"message": "Player created"},
                                     201,
                                     setCookie=True,
                                     cookie=new_player.userId)
Example #11
0
def loadPlayer(netid, uid, varname):
    RVEngine.log("Loading Player from uid " + uid)
    qo = Player().queryObject()
    p = qo.filter(Player.uid == uid).first()
    RVEngine.log("Passed filter")
    if p is None:
        RVEngine.log("Player not found, creating.")
        p = Player()
        p.uid = uid
        p.varname = varname
        p.save()
    RVEngine.log("Passed is None, got " + str(p.varname))
    p.netid = netid
    p.sync = True
    RVEngine.log("Updating player")
    # p.update()
    RVEngine.log("Loading unitdata")
    RVEngine.loadPlayer(p)
    return p
Example #12
0
 async def on_member_join(self, member):
     player = db.getPlayer(member.id)
     if not player:
         player = Player(member.id, member.nick)
     db.setPlayer(player)
Example #13
0
def query(worker_number,
          work,
          dbconf,
          token='demo',
          lang='en',
          timeout=15,
          max_retries=5,
          debug=False,
          err_queue=None,
          debug_queue=None):
    try:
        engine = create_engine(
            "{protocol}://{user}:{password}@{address}/{name}".format(**dbconf),
            echo=False)
        Session = sessionmaker(bind=engine)
        session = Session()
        data_fields = ('created_at', 'account_id', 'last_battle_time',
                       'nickname', 'updated_at', 'statistics.all.battles')
        while not work.empty():
            t_players, realm = work.get(False, 0.000001)
            retries = max_retries
            while retries:
                try:
                    response = player_data(t_players,
                                           token,
                                           fields=data_fields,
                                           language=lang,
                                           api_realm=realm,
                                           timeout=timeout)
                    pulltime = datetime.utcnow()
                    for _, player in response.iteritems():
                        if player is None or len(player) == 0:
                            continue
                        try:
                            p = session.query(Player).filter(
                                Player.account_id ==
                                player['account_id']).one()
                            p.battles = player['statistics']['all']['battles']
                            p.last_battle_time = datetime.utcfromtimestamp(
                                player['last_battle_time'])
                            p.updated_at = datetime.utcfromtimestamp(
                                player['updated_at'])
                            p._last_api_pull = pulltime
                        except NoResultFound:
                            session.add(
                                Player(
                                    account_id=player['account_id'],
                                    nickname=player['nickname'],
                                    console=realm,
                                    created_at=datetime.utcfromtimestamp(
                                        player['created_at']),
                                    last_battle_time=datetime.utcfromtimestamp(
                                        player['last_battle_time']),
                                    updated_at=datetime.utcfromtimestamp(
                                        player['updated_at']),
                                    battles=player['statistics']['all']
                                    ['battles'],
                                    _last_api_pull=pulltime))
                            # print(player['account_id'], ':', m)
                    session.commit()

                    if debug and debug_queue is not None:
                        debug_queue.put(
                            'Worker {}: Success pulling players {}'.format(
                                worker_number, map(str, t_players)))
                    del response
                    break
                except (TypeError, ConnectionError) as ce:
                    if 'Max retries exceeded with url' in str(ce):
                        retries -= 1
                    else:
                        if err_queue is not None:
                            err_queue.put((t_players, ce))
                        break
                except WOTXResponseError as wg:
                    if 'REQUEST_LIMIT_EXCEEDED' in wg.message:
                        retries -= 1
                        sleep(0.1)
                    else:
                        if err_queue is not None:
                            err_queue.put((t_players, wg))
                        break
            if not retries:
                if err_queue is not None:
                    err_queue.put(
                        (t_players, Exception('Retry limit exceeded')))
            t_players = None
    except (KeyboardInterrupt, Empty):
        pass
    except Exception as e:
        try:
            if err_queue is not None:
                err_queue.put((t_players, e))
        except:
            pass
    finally:
        try:
            session.commit()
        except:
            pass
    print('Worker{:3}: Exiting at {}'.format(
        worker_number,
        datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
Example #14
0
def getPlayerByVarname(varname):
    qo = Player().queryObject()
    p = qo.filter(Player.varname == varname).first()
    return p
    name="Gaurang datt",
    email="*****@*****.**",
    picture=
    'https://pbs.twimg.com/profile_images/2671170543/18debd694829ed78203a5a36dd364160_400x400.png'
)
session.add(User1)
session.commit()

club1 = Club(name='Real Madrid')

session.add(club1)
session.commit()

player1 = Player(name="Keylor Navas",
                 description="The keeper from costa rica ",
                 jersey="1",
                 position="GoalKeeper",
                 club=club1)
session.add(player1)
session.commit()

player2 = Player(name="Sergio Ramos",
                 description="A true leader of LOS BLANOCS",
                 jersey="4",
                 position="CenterBack",
                 club=club1)

session.add(player2)
session.commit()

player3 = Player(
Example #16
0
from attr import asdict
from database import db, Player

from battler import Battler


res = db.search(Player.exists())
if res:
    print(res[0]['player'])
else:
    name = input("Enter your name: ")
    battler = Battler(name=name)
    db.insert({'player': asdict(battler)})
Example #17
0
def getPlayerByVarname(varname):
	qo = Player().queryObject()
	p = qo.filter(Player.varname == varname).first()
	return p
Example #18
0
def dashboard():

    ad_matches = db.ad_matches()    #./dashboard

    #---------------OPERATIONS--------------------------------

    if request.method == 'POST':

        if request.form.get('operation') == 'schedule_match':

            team1 = request.form.get('team1_id')
            team2 = request.form.get('team2_id')
            date  = request.form.get('date')

            match = Match(team1_id=team1, team2_id=team2, date=date)

            db.addMatch(match)   

            return redirect(url_for('dashboard'))  

        elif request.form.get('operation') == 'delete_match':

            match_id = request.form.get('match_id')

            match = Match(match_id=match_id)

            db.deleteMatch(match)

            return redirect(url_for('dashboard'))

        elif request.form.get('operation') == 'add_team':

            name = request.form.get('team_name')
            captain = request.form.get('captain_name')

            team = Team(name=name, captain=captain)

            db.addTeam(team)

            return redirect(url_for('dashboard'))

        elif request.form.get('operation') == 'delete_team':

            id = request.form.get('team_id')

            team = Team(id=id)

            db.deleteTeam(team)

            return redirect(url_for('dashboard'))

        
        elif request.form.get('operation') == 'add_player':

            name = request.form.get('player_name')
            team_id = request.form.get('team_id')

            player = Player(name=name, team_id=team_id)

            db.addPlayer(player)

            return redirect(url_for('dashboard'))

        elif request.form.get('operation') == 'delete_player':

            id = request.form.get('player_id')
            team_id = request.form.get('team_id')

            player = Player(id=id, team_id=team_id)

            db.deletePlayer(player)

            return redirect(url_for('dashboard'))


    return render_template("./admin/dashboard.html",title="Dash Board", matches=ad_matches)