def post(self, name): data = Player.parser.parse_args() # not getting the name correctly from the url name = data["name"] if PlayerModel.find_by_name(name): return { 'message': f'A player with name {name} already exists' }, 400 data = Player.parser.parse_args() strategy = data['strategy'] buyIn = data["buyIn"] chips = data["buyIn"] unitBet = data["unitBet"] player = PlayerModel(name=name, strategy=strategy, buyIn=buyIn, chips=chips, unitBet=unitBet) # print(f'{name}:{strategy}:{buyIn}:{chips}{unitBet}') try: player.save_to_db() except: #raise return {'message': 'an error occurred inserting the player.'}, 500 #return player.json(), 201 return redirect("/", code=302)
def post(self): """ Class methods: POST Endpoint: /player-register Class method that handles post requests for the PlayerRegister Resource. Using payload from the POST request, it will use the 'playerName' and the 'secretKey' that were provided to create a new player. This class will only handle the registering process. Args: Returns: 'message' if either the user already exists or if the player was created succesfully. """ #: object of parsed items set to their appropiate type: This data is reetrieved from payload. data = PlayerRegister.__player_parse.parse_args() # Check if the player name is already taken if (PlayerModel.findByPlayerName(data['playerName'])): return {'message': 'User already exists!'}, 409 #Conflict # Uses the PlayerRegister function save_to_db() function that uses SQLAlchemys save and commit to register the player # to the database player = PlayerModel(data['playerName'], data['secretKey'], 'player', 'none', 'none', 100, 100) player.save_to_db() return {'message': 'Player was created succesfully!'}, 201
def get(self, team_name=None, division=None): if team_name is None and division is None: players = PlayerModel.query.all() else: team = TeamModel.find_by_name(team_name) if team: players = PlayerModel.find_by_team_id(team.id) else: players = PlayerModel.find_by_division(division) return {"players": [player.json() for player in players]}
def post(self, id): token = request.headers.get('authorization') if not token: return { 'error': True, 'message': 'Missing token in authorization header.' }, 401 # Gets the Room the player is currently in player_status_response = requests.get( 'https://lambda-treasure-hunt.herokuapp.com/api/adv/init/', headers={ 'authorization': token }).json() if len(player_status_response['errors']) > 0: return player_status_response, 400 time.sleep(1) # finds the the player by their unique log in token foundTraversingPlayer = PlayerModel.find_by_password(token) if foundTraversingPlayer: return { "error": True, "message": "Your character is already traversing" } # If the player is not in the DB they are added elif not foundTraversingPlayer: found_path = GraphTraversal().path_to_target( player_status_response['room_id'], id) if not found_path: return { "error": True, "message": "there is no path to that room you bonobo" } new_player_data = { "password": token, "currentRoomId": player_status_response['room_id'], "currentPath": json.dumps(found_path), "nextAvailableMove": 0, "singlePath": True } foundTraversingPlayer = PlayerModel(**new_player_data) foundTraversingPlayer.save_to_db() return {'Message': 'Target Traverse has started.'}
def get(self, name, division=None, team_name=None): if team_name is None and division is None: players = PlayerModel.find_by_name(name) if players.count() > 0: return {"players": [player.json() for player in players]} elif team_name is None: print(division) else: team = TeamModel.find_by_name_division(team_name, division) if team: players = PlayerModel.find_by_team_id(team.id) if players.count() > 0: return {"players": [player.json() for player in players]} return {"message": "Player does not exists"}
def get(cls, playerName): """ Class method: GET Endpoint: /player Class method that handles GET requests for the Player Resource. Player data retrieval is accomplished using player id supplied in the URL parameters Args: playerName: Name supplied via URL parameters Returns: 'message' if the player exists return relative data for that player, otherwise error message stating that the user was not found. """ try: #: Object of type PlayerModel: Will store an object of the player we want data from. player = PlayerModel.findByPlayerName(playerName) except: return { 'message': 'There was an error finding the player in the DB!' } if player is not None: return player.json() return {'message': 'Player was not found!'}
def delete(self, name): player = PlayerModel.find_by_name(name) if player: item.delete_from_db() return {'message': 'Player deleted'}
def delete(self, name): player = PlayerModel.find_name(name) if player: player.delete_from_db() return {"Message": "Player deleted!"} return {"Message": "Player not found"}
def post(self): data = PlayerConfrontation.parse.parse_args() currentPlayer = PlayerModel.findByPlayerId(current_identity.id) enemy = PlayerModel.findByPlayerId(data['player']) location = LocationModel.findById(currentPlayer.locationId) playerList = [] playerCount = 0 for player in location.players: if (player.role == 'player' and player.playerName != currentPlayer.playerName): playerCount = playerCount + 1 playerList.append(player.json()) if (playerCount == 0): return {'message': 'Target Selected'} else: return jsonify(playerList)
def put(self, name): data = Player.parser.parse_args() item = PlayerModel.find_name(name) if item is None: item = PlayerModel(name, data['price']) else: item.price = data['price'] item.save_to_db() return item.json()
def delete(self, name): data = Player.parser.parse_args() team = TeamModel.find_by_name(data['team_name']) if team is None: return {"message": "Team does not exist"} player = PlayerModel.find_player_in_team(name, team.id, data['back_number']) if player: player.delete_from_db() return {"message": "Player deleted"}
def get(self): """ Class method: GET Endpoint: /player-location Will return a players current location details only if that player is authorized and part of a lobby. """ player = PlayerModel.findByPlayerId(current_identity.id) if (player.locationId == -1): return {'message': 'You are not currently part of a lobby!'} location = LocationModel.findById(player.locationId) return location.json()
def put(self, name): data = Player.parser.parse_args() # not getting the name correctly from the url name = data["name"] player = PlayerModel.find_by_name(name) # PlayerModel.insert(player) if player: # update attributes player.strategy = data['strategy'] player.buyIn = data["buyIn"] player.chips = data["buyIn"] player.unitBet = data["unitBet"] else: player = PlayerModel(name=name, strategy=strategy, buyIn=buyIn, chips=chips, unitBet=unitBet) player.save_to_db() return player.json()
def delete(self): token = request.headers.get('authorization') if not token: return {'error': True, 'message': 'Missing token in authorization header.'}, 401 deletePlayer = PlayerModel.find_by_password(token) if not deletePlayer: return {'error': True, 'message': 'Player not found.'} deletePlayer.delete_from_db() return {'Message': 'Auto Traverse has been stopped.'}
async def fetch(self, include_stats=False): """ Selects given players, if include_stats then will be ordered by elo. https://github.com/ModuleLIFT/API/blob/master/docs/modules.md#fetchself-include_statsfalse """ values = dict(self.values) if include_stats: query = """SELECT IFNULL(statistics.elo, 0) AS elo, IFNULL(statistics.kills, 0) AS kills, IFNULL(statistics.deaths, 0) AS deaths, IFNULL(statistics.assists, 0) AS assists, IFNULL(statistics.shots, 0) AS shots, IFNULL(statistics.hits, 0) AS hits, IFNULL(statistics.damage, 0) AS damage, IFNULL(statistics.headshots, 0) AS headshots, IFNULL(statistics.rounds_won, 0) AS rounds_won, IFNULL(statistics.rounds_lost, 0) AS rounds_lost, IFNULL(statistics.wins, 0) AS wins, IFNULL(statistics.ties, 0) AS ties, IFNULL(statistics.loses, 0) AS loses, users.discord_id, users.name, users.user_id, users.file_type, users.steam_id, users.joined FROM users LEFT JOIN statistics ON users.user_id = statistics.user_id AND statistics.league_id = :league_id AND statistics.region = :region WHERE users.user_id IN :user_ids ORDER BY statistics.elo DESC""" values["league_id"] = self.current_league.league_id values["region"] = self.current_league.region else: query = """SELECT discord_id, name, user_id, steam_id, joined FROM users WHERE user_id IN :user_ids""" rows_formatted = [] rows_formatted_append = rows_formatted.append async for row in SESSIONS.database.iterate(query=query, values=values): player = PlayerModel(row) if include_stats: rows_formatted_append(player.full) else: rows_formatted_append(player.minimal) return Response(data=rows_formatted)
async def fetch(self, include_stats=False): """ Selects given players. """ values = dict(self.values) if include_stats: query = """SELECT IFNULL(statistics.elo, 0) AS elo, IFNULL(statistics.kills, 0) AS kills, IFNULL(statistics.deaths, 0) AS deaths, IFNULL(statistics.assists, 0) AS assists, IFNULL(statistics.shots, 0) AS shots, IFNULL(statistics.hits, 0) AS hits, IFNULL(statistics.damage, 0) AS damage, IFNULL(statistics.headshots, 0) AS headshots, IFNULL(statistics.roundswon, 0) AS roundswon, IFNULL(statistics.roundslost, 0) AS roundslost, IFNULL(statistics.wins, 0) AS wins, IFNULL(statistics.ties, 0) AS ties, IFNULL(statistics.losses, 0) AS losses, users.discord_id, users.name, users.pfp, users.user_id, users.steam_id, users.joined FROM users LEFT JOIN statistics ON users.user_id = statistics.user_id AND statistics.league_id = :league_id WHERE users.region = :region AND users.user_id IN :user_ids ORDER BY statistics.elo DESC""" values["league_id"] = self.current_league.league_id else: query = """SELECT discord_id, name, pfp, user_id, steam_id, joined FROM users WHERE region = :region AND user_id IN :user_ids""" rows_formatted = [] rows_formatted_append = rows_formatted.append async for row in self.current_league.obj\ .database.iterate(query=query, values=values): player = PlayerModel(row) if include_stats: rows_formatted_append(player.full) else: rows_formatted_append(player.minimal) return response(data=rows_formatted)
def sample_data(app, db): admin = UserModel(email='*****@*****.**', password='******') guest = UserModel(email='*****@*****.**', password='******') db.session.add(admin) db.session.add(guest) team1 = TeamModel(name='England') team2 = TeamModel(name='Australia') db.session.add(team1) db.session.add(team2) db.session.commit() player1a = PlayerModel(name='Jack', team_id=team1.id) player1b = PlayerModel(name='Jill', team_id=team1.id) db.session.add(player1a) db.session.add(player1b) player2a = PlayerModel(name='Jamie', team_id=team2.id) player2b = PlayerModel(name='James', team_id=team2.id) db.session.add(player2a) db.session.add(player2b) db.session.commit()
def put(self, name): data = Player.parser.parse_args() team = TeamModel.find_by_name(data['team_name']) if team is None: return {"message": "Team does not exist"} if PlayerModel.find_by_back_number_in_team(data['new_back_number'], team.id): return {"message": "Back number is already taken."} player = PlayerModel.find_player_in_team(name, team.id, data['back_number']) if player is None: return {"message": "Player doesn not exist"} else: if data['new_back_number'] is None: return {"message": "New Back Number is missing"} player.back_number = data['new_back_number'] player.save_to_db() return player.json()
def put(self, name): data = Player.parser.parse_args() player = PlayerModel.lookup(name) if player is None: player = PlayerModel(name, **data) player.save() return player.json()
def post(self, lobby_id): """Class Method used for POST request for game lobby data. Args: lobby_id: Id of the lobby we want to trieve data from. Return: success message, if the game lobby exists, is not full and player is not part of it error message, if is full, player is part of it or doesn't exists """ # Checking if lobby exists #: Object of type LobbyModel: Used with SQLAlchemy for access and manipulation of obj. in DB lobby = LobbyModel.findById(lobby_id) if lobby is None: return {'message': 'Lobby does not exists!'} if (lobby.lobbySize == 3): return {'message': 'Lobby is full'} # Adding player to the lobby #: str : retrieves the playerName from the current jwt token playerName = current_identity.playerName #: Object of type PlayerModel: Used with SQLAlchemy to access and manipulate the obj. in the DB player = PlayerModel.findByPlayerName(playerName) if (player.currentLobby == lobby_id): return {'message': 'You are already part of the lobby!'} elif (player.currentLobby != -1): return {'message': 'You are part of a different lobby!'} # sets playes lobbyId to the one he joined player.currentLobby = lobby.lobbyId # Increases lobby size to account new player lobby.lobbySize = lobby.lobbySize + 1 lobby.save_to_db() # Create a home for new player home = LocationModel(player.playerName, 'home') home.save_to_db() player.locationId = home.id player.homeId = home.id player.save_to_db() return {'message': 'You have succesfully joined the lobby!'}
def post(self, name): data = Player.parser.parse_args() team = TeamModel.find_by_name(data['team_name']) if team is None: return {"message": "Team does not exist"} if PlayerModel.find_by_back_number_in_team(data['back_number'], team.id): return {"message": "Back number is already taken."} player = PlayerModel(name, data['back_number'], team.id) player.save_to_db() return player.json()
def post(self, name): if PlayerModel.lookup(name): return {'message': "A player with name '{}' already exists.".format(name)}, 400 data = Player.parser.parse_args() player = PlayerModel(name, **data) try: player.save() except: return {"message": "An error occurred inserting the player."}, 500 return player.json(), 201
def post(self): """ Class method: POST Endpoint: /player-location Will change a players location depending on the id of the location they want to go. Error check must look for the following. If player is part of the lobby, """ data = PlayerLocation.parse.parse_args() player = PlayerModel.findByPlayerId(current_identity.id) if (player.locationId == data['locationId']): return {'message': 'Already at that location.'} try: currentLocation = LocationModel.findById(player.locationId) currentLocation.numOfPlayers = currentLocation.numOfPlayers - 1 player.locationId = data['locationId'] player.stamina = player.stamina - 10 newLocation = LocationModel.findById(data['locationId']) newLocation.numOfPlayers = newLocation.numOfPlayers + 1 player.save_to_db() # Save new locations currentLocation.save_to_db() newLocation.save_to_db() if (player.stamina == 0): player.status = "sleep" player.save_to_db() return { 'message': 'You are out of stamina and have fallen asleep!' } except: return {'message': 'Error saving to the DB!'} return {'message': 'You have succesfully changed locations.'}
async def players(self): """ Pulls players https://github.com/ModuleLIFT/API/blob/master/docs/modules.md#playersself """ query = """SELECT IFNULL(statistics.elo, 0) AS elo, IFNULL(statistics.kills, 0) AS kills, IFNULL(statistics.deaths, 0) AS deaths, IFNULL(statistics.assists, 0) AS assists, IFNULL(statistics.shots, 0) AS shots, IFNULL(statistics.hits, 0) AS hits, IFNULL(statistics.damage, 0) AS damage, IFNULL(statistics.headshots, 0) AS headshots, IFNULL(statistics.rounds_won, 0) AS rounds_won, IFNULL(statistics.rounds_lost, 0) AS rounds_lost, IFNULL(statistics.wins, 0) AS wins, IFNULL(statistics.ties, 0) AS ties, IFNULL(statistics.loses, 0) AS loses, users.steam_id, users.discord_id, users.name, users.file_type, users.user_id, users.joined FROM users LEFT JOIN statistics ON users.user_id = statistics.user_id AND statistics.region = :region AND statistics.league_id = :league_id WHERE users.user_id = :search OR users.steam_id = :search OR users.discord_id = :search OR users.name LIKE :search ORDER BY statistics.elo {} LIMIT :limit, :offset""".format(self.order_by) rows_formatted = [] rows_formatted_append = rows_formatted.append async for row in SESSIONS.database.iterate( query=query, values=self.values): rows_formatted_append(PlayerModel(row).full) return Response(data=rows_formatted)
async def get(self): """ Gets infomation on given player. """ query = """SELECT users.user_id, users.steam_id, users.discord_id, users.name, users.pfp, users.joined, IFNULL(statistics.total_time, 0) AS total_time, IFNULL(statistics.elo, 0) AS elo, IFNULL(statistics.kills, 0) AS kills, IFNULL(statistics.deaths, 0) AS deaths, IFNULL(statistics.assists, 0) AS assists, IFNULL(statistics.shots, 0) AS shots, IFNULL(statistics.hits, 0) AS hits, IFNULL(statistics.damage, 0) AS damage, IFNULL(statistics.headshots, 0) AS headshots, IFNULL(statistics.roundswon, 0) AS roundswon, IFNULL(statistics.roundslost, 0) AS roundslost, IFNULL(statistics.wins, 0) AS wins, IFNULL(statistics.ties, 0) AS ties, IFNULL(statistics.losses, 0) AS losses FROM users LEFT JOIN statistics ON statistics.user_id = users.user_id WHERE (users.steam_id = :user_id OR users.discord_id = :user_id OR users.user_id = :user_id) AND statistics.region = :region AND statistics.league_id = :league_id """ row = await self.current_league.obj.database.fetch_one( query=query, values=self.values ) if row: return response(data=PlayerModel(row).full) else: return response(error="Invalid user")
async def get(self): """ Gets infomation on given player. https://github.com/ModuleLIFT/API/blob/master/docs/modules.md#getself-1 """ query = """SELECT users.user_id, users.steam_id, users.discord_id, users.name, users.joined, users.file_type, IFNULL(statistics.total_time, 0) AS total_time, IFNULL(statistics.elo, 0) AS elo, IFNULL(statistics.kills, 0) AS kills, IFNULL(statistics.deaths, 0) AS deaths, IFNULL(statistics.assists, 0) AS assists, IFNULL(statistics.shots, 0) AS shots, IFNULL(statistics.hits, 0) AS hits, IFNULL(statistics.damage, 0) AS damage, IFNULL(statistics.headshots, 0) AS headshots, IFNULL(statistics.rounds_won, 0) AS rounds_won, IFNULL(statistics.rounds_lost, 0) AS rounds_lost, IFNULL(statistics.wins, 0) AS wins, IFNULL(statistics.ties, 0) AS ties, IFNULL(statistics.loses, 0) AS loses FROM users LEFT JOIN statistics ON statistics.user_id = users.user_id AND statistics.region = :region AND statistics.league_id = :league_id WHERE users.user_id = :user_id """ row = await SESSIONS.database.fetch_one(query=query, values=self.values) if row: return Response(data=PlayerModel(row).full) else: return Response(error="Invalid user")
async def players(self): """ Pulls players """ query = """SELECT IFNULL(statistics.elo, 0) AS elo, IFNULL(statistics.kills, 0) AS kills, IFNULL(statistics.deaths, 0) AS deaths, IFNULL(statistics.assists, 0) AS assists, IFNULL(statistics.shots, 0) AS shots, IFNULL(statistics.hits, 0) AS hits, IFNULL(statistics.damage, 0) AS damage, IFNULL(statistics.headshots, 0) AS headshots, IFNULL(statistics.roundswon, 0) AS roundswon, IFNULL(statistics.roundslost, 0) AS roundslost, IFNULL(statistics.wins, 0) AS wins, IFNULL(statistics.ties, 0) AS ties, IFNULL(statistics.losses, 0) AS losses, users.steam_id, users.discord_id, users.name,users.pfp, users.user_id, users.joined FROM users INNER JOIN statistics ON users.user_id = statistics.user_id WHERE users.region = :region AND users.league_id = :league_id AND (users.user_id = :search OR users.steam_id = :search OR users.discord_id = :search OR users.name LIKE :search) ORDER BY statistics.elo {} LIMIT :limit, :offset""".format(self.order_by) rows_formatted = [] rows_formatted_append = rows_formatted.append async for row in self.current_league.obj.database.iterate( query=query, values=self.values): rows_formatted_append(PlayerModel(row).full) return response(data=rows_formatted)
def post(self, name): if PlayerModel.find_name(name): return { 'message': "An item with name '{}' already exists.".format(name) }, 400 data = Player.parser.parse_args() item = PlayerModel(name, **data) try: item.save_to_db() except: return {"message": "An error occurred inserting the item."}, 500 return item.json(), 201 players.append(player) return player
def start_loop(self): with self.app.app_context(): directions = ['n', 'e', 's', 'w'] while True: time.sleep(1) # Get all players who are automatically traversing traversing_players = PlayerModel.find_all_by_single_path(True) if not traversing_players or len(traversing_players) < 1: print('No one traversing via target. Skip.') continue # Make every record of traversing_players the JSON dict available. for player in traversing_players: player_data = player.json() # Only register next move if the player is passed cooldown. if int(time.time()) < player_data['nextAvailableMove'] + 2: time.sleep(player_data['nextAvailableMove'] + 1 - int(time.time())) player_path = json.loads( player_data["currentPath"])["path"] # Player has a path, travel based on it. if len(player_path) > 0: direction = player_path.pop(0) traverse_to_room = Traverse.TraverseOnce( player_data['password'], direction) traverse_to_room = traverse_to_room[0] if len(traverse_to_room['errors']) > 0: print(traverse_to_room['errors'], "ERROR", traverse_to_room['cooldown']) setattr(player, 'nextAvailableMove', (int(time.time()) + 2 + int(traverse_to_room['cooldown']))) self.save_player(player) # player.save_to_db() continue setattr( player, 'nextAvailableMove', int(time.time()) + 2 + int(traverse_to_room['cooldown'])) setattr(player, 'currentRoomId', traverse_to_room['room_id']) setattr(player, 'currentPath', json.dumps({"path": player_path})) # player.save_to_db() self.save_player(player) print( f"player traveled {direction} to {traverse_to_room['room_id']}" ) continue # return traverse_to_room else: print("player has finished traversal") delete_player = player.find_by_password( player_data["password"]) print(delete_player, "tester") if delete_player: delete_player.delete_from_db()
def get(self, name): player = PlayerModel.find_by_name(name) if player: return player.json() return {'message': 'Player not found'}, 404