class Games(): ''' Games Class ''' def __init__(self): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self): ''' Get all movies ''' self.logger.info(list(self.collection.find({}))) return {'result': list(self.collection.find({}, {'_id': 0}))}, 200 # return { # 'games':[ # {'gameTitle': 'game1', # 'gameGenre': 'genre1'}, # {'gameTitle': 'game2', # 'gameGenre': 'genre2'}, # ] # }, 200 def get_one(self, title): ''' Get one game by title ''' result = self.collection.find_one({'title': title}, {'_id': 0}) if result: return result, 200 return {'message': f' {title} not found'}, 404 def create_one(self, payload): ''' Create a game ''' added_title = self.collection.find_one(payload) if added_title: return { 'message': f'Duplicate Error {payload} already in database' } self.collection.insert_one(payload) return { 'message': f'Created game: {payload}', 'gameTitle': f'{payload["title"]}', 'gameGenre': f'{payload["genre"]}', }, 201 def update_one(self, title, payload): ''' update one game by title ''' result = self.collection.find_one({'title': title}, {'_id': 0}) if result: self.collection.update_one({'title': title}, {'_id': 0}) return {'message': f'Updated {title}'}, 200 return {'message': f'{title} not found'}, 404 def delete_one(self, title): ''' delete one game by title ''' result = self.collection.find_one({'title': title}, {'_id': 0}) if result: self.collection.delete_one(result) return {'message': f'{title} successfully deleted from db'}, 200 return {'message': f'{title} not found'}, 404
class Movies(): ''' Items class ''' def __init__(self): self.class_name = type(self).__name__ # Contact self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self): ''' get all items ''' return {'results': list(self.collection.find({}, {'_id': 0}))}, 200 def get_one(self, name): ''' get one item by name ''' find_one = self.collection.find_one({'name': name}, {'_id': 0}) if find_one: return find_one return {'message': f'not found item {name}'}, 404 def create_one(self, payload): ''' Create an movie ''' find = self.collection.find_one(payload) if find: return {'message': f'Item {payload} already exists'}, 400 self.collection.insert_one(payload) return { 'message': f'Created item: {payload}', 'itemName': f'{payload["name"]}', 'itemGenre': f'{payload["genre"]}', }, 201 def update_one(self, name, payload): ''' update one movie by name ''' result = self.collection.find_one({'name': name}, {'_id': 0}) if result: self.collection.update_one({"name": name}, {"$set": payload}) return {'message': f'Updated {name}'}, 200 return {'message': f'{name} not found'}, 404 def delete_one(self, name): ''' delete one movie by name ''' result = self.collection.delete_one({'name': name}) if result.deleted_count: return {'message': f'Deleted {name} successfully'}, 200 return {'message': f'No movie found with name = {name}'}, 404
class Movies(): ''' Movies class ''' def __init__(self): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self): ''' get all movies ''' self.logger.info(list(self.collection.find({}))) return {'result': list(self.collection.find({}, {'_id': 0}))}, 200 def get_one(self, name): ''' get one movie by name ''' result = self.collection.find_one({'name': name}, {'_id': 0}) if result: return result, 200 return {'message': f'{name} not found'}, 404 def create_one(self, payload): ''' Create an movie ''' self.collection.insert_one(payload) return {'message': f'Created movie: {payload}'}, 201 def update_one(self, name, payload): ''' update one movie by name ''' result = self.collection.find_one({'name': name}, {'_id': 0}) if result: self.collection.update_one({"name": name}, {"$set": payload}) return {'message': f'Updated {name}'}, 200 return {'message': f'{name} not found'}, 404 def delete_one(self, name): ''' delete one movie by name ''' return {'message': f'Delete {name}'}, 200
class Contact(): ''' Contact class ''' def __init__(self): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def add_item(self, item): ''' Add an item to the database ''' self.collection.insert_one(item) def find_one_item(self, query): ''' find a item in collection ''' return self.collection.find_one(filter=query) def find_many_item(self, query): ''' find a item in collection ''' return self.collection.find_many(filter=query) def add_multiple(self, lists): '''insert multiple posts or documents''' return self.collection.insert_many(documents=lists) def find_all(self): '''returns all documents or a collection''' results = self.collection.find({}) for result in results: print(result) # def find_multiple(self, results, result): # '''finds multiple documents''' # results = self.collection.find(result) # for result in results: # return results def delete_one_item(self, delt): # what is the filter from '''delete one item''' return self.collection.delete_one(filter=delt) def delete_clear(self): '''clear database''' return self.collection.delete_many({}) def update_first_name(self, firstName): change = input('New name? ') return self.collection.update_one({'firstName': firstName}, {'$set': {'firstName': change}})
class Contact(): ''' Contact class ''' def __init__(self): self.class_name = type(self).__name__ # Contact self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def add_item(self, item): ''' Add an item to the database ''' if self.find_one(query={ 'firstName': item['firstName'], 'lastName': item['lastName']}): self.logger.error('Contact already exists for %s %s', item['firstName'], item['lastName']) return self.logger.info('Contact %s %s added successfully', item['firstName'], item['lastName']) self.collection.insert_one(item) def find_one(self, query): ''' find a item in collection ''' return self.collection.find_one(filter=query) def find_many(self, query): ''' find a item in collection ''' return self.collection.find(filter=query) def delete_one(self, query): ''' delete an item from collection ''' return self.collection.delete_one(filter=query) def delete_many(self, query): ''' delete an item from collection ''' return self.collection.delete_many(filter=query) def update(self, query, update_dict): ''' update a item in the collection ''' result = self.collection.update_one(filter=query, update=update_dict) if result.modified_count == 0: self.logger.warning('Nothing changed') else: self.logger.info('New -> %s', self.find_one(query=query))
class Players(): ''' Players class ''' def __init__(self): self.class_name = type(self).__name__ # Contact self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self, level=None, state=None): ''' get all items ''' self.logger.info('level=%s state=%s', level, state) self.logger.info(list(self.collection.find({}))) query = {} if level: query['level'] = level self.logger.info('QUERY %s', query) if state: query['state'] = state self.logger.info('QUERY %s', query) return {'results': list(self.collection.find(query, {'_id': 0}))}, 200 def get_one(self, username): ''' gets player by username ''' find_one = self.collection.find_one({'username': username}, {'_id': 0}) if find_one: return find_one return {'message': f'UserName {username} not found'}, 404 def get_user_state(self, username): '''gets a userstate''' results = self.collection.find({'username': username}, {'_id': 0}) if results: for result in results: return result['state'], 200 return { 'message': f'Contact Username State {username} not found ' }, 404 def create_one(self, payload): ''' Create an username ''' find_username = self.collection.find_one( {'username': payload['username']}, {'_id': 0}) find_displayname = self.collection.find_one( {'displayName': payload['displayName']}, {'_id': 0}) if find_displayname: return {'message': f'{payload["displayName"]} already exists'}, 409 if find_username: return {'message': f'{payload["username"]} already exists'}, 409 resp, code = self.validate_schema(payload) if code != 200: return resp, code self.collection.insert_one(payload) return {'message': f'Created Username: {payload}'}, 201 def update_one(self, username, payload): ''' updates player by username''' result = self.collection.find_one({'username': username}, {'_id': 0}) print(result) if result: self.collection.update_one({"username": username}, {"$set": payload}) return {'message': f'Updated {username}'}, 200 return {'message': f'Player {username} not found'}, 404 def update_one_state(self, username, state): ''' updates player state by username ''' results = self.collection.find_one({"username": username}, {'_id': 0}) if results: self.collection.update_one({"username": username}, {"$set": state}) return {'message': f'Updated {username}'}, 200 return {'message': f'Player {username} not found'}, 404 def delete_one(self, username): ''' deletes player by username ''' result = self.collection.delete_one({'username': username}) if result: return {'message': f'Deleted {username} successfully'}, 200 return {'message': f'No contact found with name = {username}'}, 404 def validate_schema(self, payload): """ Validates application definiition against schema """ schema = load_json_schema('username-schema.json') try: validate(payload, schema) except ValidationError as v_err: self.logger.warning('Schema validation error: %s', v_err) return { 'error': 'Failed schema validation', 'message': v_err.message, 'data': payload }, 422 except Exception as ex: # pylint: disable=broad-except self.logger.error('Unknown schema validation error: %s', ex) return { 'error': 'Unkown schema validation', 'message': ex, 'data': payload }, 400 return { 'message': 'Application defininion passed schema validation' }, 200
class Movie(): ''' Contact class ''' #MIGHT HAVE TO MOVE THE CONSTRUCTORS TO A NEW py class def __init__(self, name=None, director=None, starring=None, category=None): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) self.name = name self.director = director self.starring = starring self.category = category # cd.collection.insert_one(item) def add_item(self, item): # how did we place the inputs here before? ''' Add an item to the database ''' if self.find_one(query={ #just change the contents? 'movieName': item['movieName'] }): self.logger.error('Movie already exists for %s', item['movieName']) return self.logger.info('Movie %s added successfully', item['movieName']) self.collection.insert_one(item) def find_one(self, query): ''' find a item in collection ''' return self.collection.find_one(filter=query) def find_many(self, query): ''' find a item in collection ''' return self.collection.find(filter=query) def delete_one(self, query): ''' delete an item from collection ''' return self.collection.delete_one(filter=query) def delete_many(self, query): ''' delete an item from collection ''' return self.collection.delete_many(filter=query) def update(self, query, update_dict): ''' update a item in the collection ''' result = self.collection.update_one(filter=query, update=update_dict) if result.modified_count == 0: self.logger.warning('Nothing changed') else: self.logger.info('New -> %s', self.find_one(query=query)) ###################sets_and_gets########################## # def get(self): # return {'movieName': self.name} #Movie({'movieName': input('What is the Movie Name? ').lower().strip(' ')}) def get(self): ''' returns address ''' return { 'name': self.name, 'starring': self.starring, 'director': self.director, 'category': self.category, } def set_name(self, name): self.name = name def get_name(self, name): return self.name def set_director(self, director): self.director = director def get_director(self, director): return self.director def set_category(self, category): self.category = category def get_category(self, category): return self.category
class Games(): ''' Games class ''' def __init__(self): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self, gameName=None, board=None, status=None, message=None, playerUp=None, playerRed=None, plyayerYellow=None): query = {} return {'result': list(self.collection.find(query, {'_id': 0}))}, 200 def get_one(self, game_id): ''' get one game by game name ''' result = self.collection.find_one({'gameId': int(game_id)}, {'_id': 0}) if result: return result, 200 return {'message': f'gameId {game_id} not found'}, 404 def create_one(self, payload): ''' create a game ''' resp, code = self.validate_schema(payload) print('block 1') if code != 200: print('block 2') return resp, code #new game_id result = list( self.collection.find({ 'gameId': { '$ne': None } }, { '_id': 0, 'gameId': 1 }).sort('gameId', -1).limit(1)) if result: next_game_id = int(result[0]['gameId']) + 1 else: next_game_id = 0 # sets game_id payload['gameId'] = next_game_id self.collection.insert_one(payload) return {'message': f'Created game: {payload}'}, 201 def delete_one(self, game_id): ''' delete a game by game name ''' result = self.collection.find({'gameId': int(game_id)}, {'_id': 0}) print(f'object{result}') print("deleteblock 1-----------------------------") if result: #------------------------------------its not finding the result? print('deleteblock 2==========================') self.collection.delete_one({'gameId': int(game_id)}) ##PROBLEM print('deleteblock 3-.-.-.-.-.-.-.-.-.-.-.-.-.-.-') return {'message': f'Deleted game with gameId {game_id}'}, 200 return {'messsage': f'{game_id} not found'}, 404 def update_one(self, game_id, payload): ''' update a game by game_id ''' print('update_one') result = self.collection.find({'gameId': int(game_id)}, {'_id': 0}) # someting here not working print('update 1') if result: print('update 2') print('through name check') self.collection.update_one({'gameId': int(game_id)}, {"$set": payload}) return {'message': f'Updated game with gameId {game_id}'}, 200 return {'message': f'gameId {game_id} not found'}, 404 def validate_schema(self, payload): ''' validates schema application definition against schema ''' schema = load_json_schema('games-schema.json') try: validate(payload, schema) except ValidationError as v_err: self.logger.warning('Schema validation error: %s', v_err) return { 'error': 'Failed schema validation', 'message': v_err.message, 'data': payload }, 422 except Exception as ex: self.logger.error('Unknown schema validation error: %s', ex) return { 'error': 'Failed schema validation', 'message': ex, 'data': payload }, 400 return { 'message': 'Application definition passed schema validation' }, 200
class Players(): '''Game class''' def __init__(self): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self, emailAddress=None, username=None, password=None, displayName=None, level=None, cumulativeScore=None, gameId=None, avatar=None, state=None): #self.logger.info('emailAddress=%s username=%s password=%s displayName=%s', emailAddress, username, password, displayName) #self.logger.info(list(self.collection(find({}))) query = {} return {'result': list(self.collection.find(query, {'_id': 0}))}, 200 def get_one(self, username): ''' get one player profile by name ''' result = self.collection.find_one({'username': username}, {'_id': 0}) if result: return result, 200 return {'message': f'{username} not found'}, 404 def create_one(self, payload): ''' create a player ''' user_found = self.collection.find_one( {'username': payload["username"]}, {'_id': 0}) if user_found: return {'message': f"{payload['username']} already exists"} resp, code = self.validate_schema(payload) if code != 200: return resp, code self.collection.insert_one(payload) return {'message': f'Created player: {payload}'}, 201 def update_one(self, username, payload): ''' update a player by username ''' result = self.collection.find_one({'username': username}, {'_id': 0}) print('update_one1') if result: print(result) self.collection.update_one({"username": username}, {"$set": payload}) return {'message': f'Updated {username}'}, 200 return {'message': f'{username} not found'}, 404 def update_many(self, username, password, payload): ''' update a player by username ''' result = self.collection.find({'username': username}, {'password': password}) if result: self.collection.update_many({"username": username}, {"$set": payload}) return {'message': f'Updated {username}'}, 200 return {'message': f'{username} not found'}, 404 def delete_one(self, username): ''' deletes a player by username ''' result = self.collection.find_one({"username": username}, {"_id": 0}) print(result) print('here') if result: print('here2') self.collection.delete_one({'username': username}, {'_id': 0}) #PROBLEM LINE print('here3') return {'message': f'Deleted {username}'}, 200 return {'message': f'{username} not found'}, 404 def validate_schema(self, payload): ''' validates schema application definition against schema ''' schema = load_json_schema('game-schema.json') try: validate(payload, schema) except ValidationError as v_err: self.logger.warning('Schema validation error: %s', v_err) return { 'error': 'Failed schema validation', 'message': v_err.message, 'data': payload }, 422 except Exception as ex: self.logger.error('Unknown schema validation error: %s', ex) return { 'error': 'Failed schema validation', 'message': ex, 'data': payload }, 400 return { 'message': 'Application definition passed schema validation' }, 200 def get_history(self, username): return self.collection_name.find({"username": username})
class Games(): ''' Games class ''' def __init__(self): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) self.board = None def get_all(self, status=None): ''' get all Games ''' query = {} # board = pickle.loads(record['board']) if status: query["status"] = status return { 'result': list(self.collection.find(query, {'_id': 0})) }, 200 def get_one(self, game_id): ''' Gets one game by game_id ''' find_one = self.collection.find_one({'game_id': int(game_id)}, {'_id': 0}) if find_one: return find_one return { 'message': f'Game ID number {game_id} not found' }, 404 def create_one(self, payload): '''Create a Game''' board = np.zeros((ROW_COUNT, COL_COUNT)) print(board) resp, code = self.validate_schema(payload) if code != 200: return resp, code # New game_id result = list(self.collection.find( {'game_id': {'$ne': None}}, {'_id': 0, 'game_id': 1} ).sort('game_id', -1).limit(1)) if result: next_game_id = int(result[0]['game_id']) + 1 else: next_game_id = 0 payload['game_id'] = next_game_id payload['board'] = board.tolist() print(type(board.tolist())) self.create_turn_counter(payload) self.collection.insert_one(payload) return { 'message': f'Created game: {payload}' }, 201 def update_one(self, game_id, payload): ''' updates one game by game_id ''' result = self.collection.find_one({'game_id': int(game_id)}, {'_id': 0}) if result: self.collection.update_one({'game_id': int(game_id)}, {'$set': payload}) return {'message': f'Updated Game ID{game_id} {payload}'}, 200 return { 'message': f'Game ID {game_id}, not found' }, 404 def delete_one(self, game_id): '''delete a Game by game_id''' result = self.collection.delete_one({'game_id': int(game_id)}) if result.deleted_count: self.collection.delete_one({'game_id': game_id}) return {'message': f'Deleted Game ID{list(game_id)}'}, 200 return {'message': f'No game with Game ID{game_id}found'}, 404 def validate_schema(self, payload): """ Validates application definiition against schema """ schema = load_json_schema('game-schema.json') try: validate(payload, schema) except ValidationError as v_err: self.logger.warning('Schema validation error: %s', v_err) return { 'error': 'Failed schema validation', 'message': v_err.message, 'data': payload }, 422 except Exception as ex: # pylint: disable=broad-except self.logger.error('Unknown schema validation error: %s', ex) return { 'error': 'Unkown schema validation', 'message': ex, 'data': payload }, 400 return { 'message': 'Application defininion passed schema validation' }, 200 def update_game_player(self, game_id, color, player_id): """ Assign Player Color with Player ID """ game_result = self.collection.find_one({'game_id': int(game_id)}, {'_id': 0}) gstat = self.game_status_chk(color, game_id, game_result) pstat = self.player_status_chk(player_id) if pstat == player_id and gstat == game_id: self.collection.update_one({'game_id': int(game_id)}, {'$set': {color: player_id}}) Players().collection.update_one({'player_id': float(player_id)}, {'$set': {"status": "IN_GAME"}} ) gstat_changer = self.game_status_changer(game_id) return { 'message': f'Player {color} added [id={player_id}] {gstat_changer}' }, 200 return { 'game': f"{pstat} {gstat}" }, 400 def update_player_move(self, game_id, color, column_number): """ Updates board with player reds move """ result = self.collection.find_one({'game_id': int(game_id)}, {'_id': 0}) player_id = result[color] column_number = int(column_number) board = result['board'] turn = result['playerUp'] turn_chk = self.turn_chk(turn, board, column_number, player_id, game_id, color, result ) if result["status"] != "IN_ACTION": return { 'message': f'Game {game_id} is not Available!' }, 400 if turn_chk: print(self.print_board(board)) return turn_chk def is_valid_location(self, board, column_number, player_id, game_id, color, result ): """ Checks if Row is valid by search for 0 in column """ if board[ROW_COUNT - 1][column_number] == 0: row = self.next_open_row(board, column_number) play = self.play_drop(board, row, column_number, player_id) next_up = self.nextup(color) self.collection.update_one( {'game_id': int(game_id)}, { '$set': { 'board': board, 'playerUp': next_up }, '$inc': {'turn_count': 1} } ) if self.win_chk(board, play) is True: self.ends_game(game_id, player_id, board, result) print("winner-----") return { "message": f"{color} moved {next_up} is next" } else: return { 'message': f'Row is full at {column_number} !' }, 400 @staticmethod def next_open_row(board, column_number): """ Looks for Next Available Row """ print("next open --") for row in range(ROW_COUNT): if board[row][column_number] == 0: return row @staticmethod def play_drop(board, row, col, play): """ Places Board Play """ print("play drop -- ") board[row][col] = play return play @staticmethod def print_board(board): """ Prints Board and flips """ # board = np.fromiter(board) return np.flip(board, 0) @staticmethod def create_turn_counter(payload): """Creates a turn counter""" turn_count = random.randint(0, 50) payload['turn_count'] = turn_count if turn_count % 2 == 0: payload['playerUp'] = 'player_red' payload['playerUp'] = 'player_yellow' def turn_chk(self, turn, board, column_number, player_id, game_id, color, result): """ Entry Point Checks for turn through color variable against turn """ validate_location = self.is_valid_location(board, column_number, player_id, game_id, color, result ) if color == turn: return validate_location else: return { "message": f"Sorry turn = {turn}!" }, 400 @staticmethod def nextup(color): """ Tracks next Player """ if color == 'player_red': return 'player_yellow' if color == 'player_yellow': return 'player_red' def game_status_changer(self, game_id): """ Checks for Game Player Vacancy """ result = self.get_one(game_id) yellow_stat = float(result['player_yellow']) red_stat = float(result['player_red']) if yellow_stat != 0 and red_stat != 0: self.collection.update_one({'game_id': int(game_id)}, {'$set': {"status": "IN_ACTION"}}) return { 'message': f"{yellow_stat} and {red_stat} are now playing" }, 201 return { 'message': f"Game still needs players" }, 200 @staticmethod def player_status_chk(player_id): """ Checks player Status to add to game """ player_result = Players().get_one_player_id(float(player_id)) if isinstance(player_result, dict): player_status = player_result['status'] if player_status == "LOBBY": return player_id return { "message": f"Player {player_id} is not eligible to join" }, 400 return { "message": f"Player {player_id} could not be found!" }, 400 @staticmethod def game_status_chk(color, game_id, game_result): """Checks game Status to add player red""" # Checks if game exists and if player spot is empty player_color = color if game_result: game_status = float(game_result[color]) if game_status == 0: return game_id return { "message": f"Sorry {player_color} taken for {game_id} !" }, 400 return { "message": f"Sorry game id {game_id} could not be found!" }, 400 def win_chk(self, board, play): """ Looks for Win """ if self.win_chk_diag_down(board, play): return True if self.win_chk_diag_up(board, play): return True if self.win_chk_horizontals(board, play): return True if self.win_chk_verticals(board, play): return True def ends_game(self, game_id, player_id, board, result): """ Ends game Resets Players declares winner """ self.reset_players(result) self.collection.update_one({"game_id": int(game_id)}, {'$set': {'status': 'win', 'player_yellow': 0, 'player_red': 0, 'winner': (player_id)}}) print(self.print_board(board)) return { 'message': f'Winner!! {player_id}, has won!!', 'Game Status': f'Game number {game_id} is over!!' }, 200 @staticmethod def reset_players(result): """Resets Players to Lobby""" Players().collection.update_one( {"player_id": int(result["player_yellow"])}, {'$set': {'status': 'IN_LOBBY'}}) Players().collection.update_one( {"player_id": int(result["player_red"])}, {'$set': {'status': 'IN_LOBBY'}}) @staticmethod def win_chk_verticals(board, play): """Win Check""" print(f"---play = {play}") print("hecking verticalsttttttt") # Checks Vertical Wins for col in range(COL_COUNT): for row in range(ROW_COUNT - (WIN_COUNT - 1)): print("inside for vertical loop") if board[row][col] == play: win_cycle = 1 while True: print(f"{row} --{col}") row += 1 if board[row][col] == play: win_cycle += 1 if win_cycle == WIN_COUNT: print("win") return True if board[row][col] != play: break @staticmethod def win_chk_horizontals(board, play): """Checks the Vertical wind""" # Checks Horizontal Wins for col in range(COL_COUNT - (WIN_COUNT - 1)): for row in range(ROW_COUNT): if board[row][col] == play: win_cycle = 1 while True: col += 1 if board[row][col] == play: win_cycle += 1 if win_cycle == WIN_COUNT: print("win") return True if board[row][col] != play: break @staticmethod def win_chk_diag_down(board, play): """Checks Diagonal Win top to Bottom""" # check diagonal top down for col in range(COL_COUNT - (WIN_COUNT - 1)): for row in range(ROW_COUNT - (WIN_COUNT - 1)): if board[row][col] == play: win_cycle = 1 while True: col += 1 row += 1 if board[row][col] == play: win_cycle += 1 if win_cycle == WIN_COUNT: print("win") return True if board[row][col] != play: break @staticmethod def win_chk_diag_up(board, play): """Check Diagonal win Bottom to Top""" # check diagonal bottom up for col in range(COL_COUNT - (WIN_COUNT - 1)): for row in range((WIN_COUNT - 1), ROW_COUNT): if board[row][col] == play: win_cycle = 1 while True: row -= 1 col += 1 if board[row][col] == play: win_cycle += 1 if win_cycle == WIN_COUNT: print("win") return True if board[row][col] != play: break
class Contacts(): ''' Contact class ''' def __init__(self): self.class_name = type(self).__name__ # Contact self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self, name=None, address=None, phoneNumber=None, isDeceased=None): ''' get all contacts ''' self.logger.info('name=%s address=%s phoneNumber=%s isDeceased=%s', name, address, phoneNumber, isDeceased) self.logger.info(list(self.collection.find({}))) # add query parameters for if they are passed query = {} if name: query['name'] = name # query = {'name': 'Dean'} self.logger.info('name: %s', query) if address: query[ 'address'] = address # query = {'name': 'Dean', 'address': '12345 street'} self.logger.info('address: %s', query) if phoneNumber: query['phoneNumber'] = phoneNumber self.logger.info('phoneNumber: %s', query) if isDeceased is not None: query['isDeceased'] = isDeceased # query = {'isDeceased': True} self.logger.info('isDeceased: %s', query) return {'result': list(self.collection.find(query, {'_id': 0}))}, 200 def get_one(self, name): ''' get one contact ''' result = self.collection.find_one({'name': name}, {'_id': 0}) if result: return result, 200 return {'message': f'{name} not found'}, 404 def create_one(self, payload): ''' Create a Contact ''' added_contact = self.collection.find_one(payload) if added_contact: return {'message': f' {payload} already in contacts'}, 409 self.collection.insert_one(payload) return { 'message': f'Created Contact: {payload}', 'name': f'{payload["name"]}', 'address': f'{payload["address"]}', 'phoneNumber': f'{payload["phoneNumber"]}', }, 201 def update_one(self, name, payload): ''' update a contact by name ''' result = self.collection.find_one({'name': name}, {'_id': 0}) if result: self.collection.update_one({'name': name}, {'$set': payload}) return {'message': f'Updated {name}'}, 200 return {'message': f'{name} not found'}, 404 def delete_one(self, name): ''' delete a contact by name ''' result = self.collection.find_one({'name': name}, {'_id': 0}) if result: self.collection.delete_one(result) return {'message': f'{name}- deleted from db'}, 200 return {'message': f' {name} not found'}, 404 def validate_schema(self, payload): ''' Validates application definition against schema ''' schema = load_json_schema('contact-schema.json') try: validate(payload, schema) except ValidationError as v_err: self.logger.warning('Schema validation error: %s', v_err) return { 'error': 'Failed schema validation', 'message': v_err.message, 'data': payload }, 422 except Exception as ex: # pylint: disable=broad-except self.logger.error('Unknown schema validation error: %s', ex) return { 'error': 'Unknown schema validation', 'message': ex, 'data': payload }, 400 return { 'message': 'Application definition passed schema validation' }, 200
class Players(): ''' Players class ''' def __init__(self): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self, status=None): ''' Gets all Players ''' query = {} if status: query["status"] = status return {'result': list(self.collection.find(query, {'_id': 0}))}, 200 def get_one_player_id(self, player_id): ''' Gets one player by player_id ''' find_one = self.collection.find_one({'player_id': int(player_id)}, {'_id': 0}) if find_one: return find_one return {'message': f'Player ID number {player_id} not found'}, 404 def create_one(self, payload): '''Creates a Player ''' chk_display_name = self.collection.find_one( {'playerDisplayName': payload['playerDisplayName']}) if chk_display_name: return { 'message': f"{payload['playerDisplayName']} already exists!" }, 409 resp, code = self.validate_schema(payload) if code != 200: return resp, code # New player_id result = list( self.collection.find({ 'player_id': { '$ne': None } }, { '_id': 0, 'player_id': 1 }).sort('player_id', -1).limit(1)) if result: next_player_id = float(result[0]['player_id']) + 1 else: next_player_id = 1 # Sets the player_id payload['player_id'] = next_player_id self.collection.insert_one(payload) return {'message': f'Created player: {payload}'}, 201 def update_one_by_id(self, player_id, payload): """ Updates Player by player_id """ result = self.collection.find_one({'player_id': int(player_id)}, {'_id': 0}) if result: self.collection.update_one({'player_id': int(player_id)}, {'$set': payload}) return {'message': f'Updated Player ID {player_id} {payload}'}, 200 return {'message'} def validate_schema(self, payload): """ Validates application definiition against schema """ schema = load_json_schema('player-schema.json') try: validate(payload, schema) except ValidationError as v_err: self.logger.warning('Schema validation error: %s', v_err) return { 'error': 'Failed schema validation', 'message': v_err.message, 'data': payload }, 422 except Exception as ex: # pylint: disable=broad-except self.logger.error('Unknown schema validation error: %s', ex) return { 'error': 'Unkown schema validation', 'message': ex, 'data': payload }, 400 return { 'message': 'Application defininion passed schema validation' }, 200
class Players(): ''' Players class ''' def __init__(self): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self, playerId=None, displayName=None): # self.logger.info('playerId=%s displayName=%s', playerId, displayName) # self.logger.info(list(self.collection.find({})) query = {} return {'result': list(self.collection.find(query, {'_id': 0}))}, 200 def get_one(self, display_name): ''' get one player by display name''' result = self.collection.find_one({'displayName': display_name}, {'_id': 0}) if result: return result, 200 return {'message': f'{display_name} not found'}, 404 def create_one(self, display_name, payload): ''' create a player ''' display_name_check = self.collection.find( {'displayName': display_name}, {'_id': 0}) print(f'display_name_check: {display_name_check}') if display_name_check: return { 'Message': f'This displayName already exists' }, 400 # or 412? resp, code = self.validate_schema(payload) if code != 200: return resp, code result = list( self.collection.find({ 'playerId': { '$ne': None } }, { '_id': 0, 'playerId': 1 }).sort('playerId', -1).limit(1)) if result: next_player_id = int(result[0]['playerId']) + 1 else: next_player_id = 0 #sets playerId payload['playerId'] = next_player_id self.collection.insert_one(payload) return {'message': f'Created player: {payload}'}, 201 def update_one(self, display_name, payload): ''' update a player by display name ''' result = self.collection.find_one({'displayName': display_name}, {'_id': 0}) if result: self.collection.update_one({'displayName': display_name}, {'$set': payload}) return {'message': f'Updated {display_name} {payload}'}, 200 return {'message': f'playerId {display_name} not found'}, 404 def delete_one(self, display_name): ''' delete a player by display name ''' result = self.collection.find_one({'displayName': display_name}, {'_id': 0}) if result: self.collection.delete_one({'displayName': display_name}) return {'message': f'deleted {display_name} successfully'}, 200 return {'message': f'displayName {display_name} not found'}, 404 def validate_schema(self, payload): '''validates schema application definition against schema ''' schema = load_json_schema('players-schema.json') try: validate(payload, schema) except ValidationError as v_err: self.logger.warning('Schema validation error: %s', v_err) return { 'error': 'Failed schema validation', 'message': v_err.message, 'data': payload }, 422 except Exception as ex: self.logger.error('Unknown schema validation error: %s', ex) return { 'error': 'Failed schema validation', 'message': ex, 'data': payload }, 400 return { 'message': 'Application definition passed schema validation' }, 200
class Contacts(): ''' Contact class ''' def __init__(self): self.class_name = type(self).__name__ # Contact self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self, phonetype_one=None, phonetype_two=None, phonetype_three=None, first_name=None, last_name=None): ''' get all items ''' query = {} if phonetype_one: query["phonetypeOne"] = phonetype_one if phonetype_two: query["phonetypeTwo"] = phonetype_two if phonetype_three: query["phonetypeThree"] = phonetype_three if first_name: query["firstName"] = first_name if last_name: query["lastName"] = last_name print(query) return {'results': list(self.collection.find(query, {'_id': 0}))}, 200 def get_one(self, contact_id): ''' get one contact by contact_Id ''' find_one = self.collection.find_one({'contact_id': int(contact_id)}, {'_id': 0}) if find_one: return find_one return {'message': f'Contact Id number {contact_id} not found'}, 404 def create_one(self, payload): ''' Create an contact ''' resp, code = self.validate_schema(payload) if code != 200: return resp, code # New Contact ID Formula result = list( self.collection.find({ 'contact_id': { '$ne': None } }, { '_id': 0, 'contact_id': 1 }).sort('contact_id', -1).limit(1)) if result: next_contact_id = int(result[0]['contact_id']) + 1 else: next_contact_id = 0 # Sets new Contact ID payload['contact_id'] = next_contact_id self.collection.insert_one(payload) return {'message': f'Created contact: {payload}'}, 201 def update_one(self, contact_id, payload): ''' update one contact by name ''' result = self.collection.find_one({'contact_id': int(contact_id)}, {'_id': 0}) if result: self.collection.update_one({"contact_id": int(contact_id)}, {"$set": payload}) return {'message': f'Updated {contact_id}'}, 200 return {'message': f'Contact number {contact_id} not found'}, 404 def delete_one(self, name): ''' delete one contact by name ''' result = self.collection.delete_one({'Name': name}) if result.deleted_count: return {'message': f'Deleted {name} successfully'}, 200 return {'message': f'No contact found with name = {name}'}, 404 def validate_schema(self, payload): """ Validates application definiition against schema """ schema = load_json_schema('contact-schema.json') try: validate(payload, schema) except ValidationError as v_err: self.logger.warning('Schema validation error: %s', v_err) return { 'error': 'Failed schema validation', 'message': v_err.message, 'data': payload }, 422 except Exception as ex: # pylint: disable=broad-except self.logger.error('Unknown schema validation error: %s', ex) return { 'error': 'Unkown schema validation', 'message': ex, 'data': payload }, 400 return { 'message': 'Application defininion passed schema validation' }, 200
class Movies(): ''' Movies class ''' def __init__(self): self.class_name = type(self).__name__ self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self, genre=None, in_theaters=None): ''' get all movies ''' self.logger.info('genre=%s in_theaters=%s', genre, in_theaters) self.logger.info(list(self.collection.find({}))) # Add query parameters if they are passed in query = {} if genre: query['genre'] = genre self.logger.info('QUERY lookie like this: %s', query) if in_theaters is not None: # Make sure we also add to query if False query['inTheaters'] = in_theaters self.logger.info('QUERY lookie like this: %s', query) return { 'result': list(self.collection.find(query, {'_id': 0})) }, 200 def get_one(self, name): ''' get one movie by name ''' result = self.collection.find_one({'name': name}, {'_id': 0}) if result: return result, 200 return {'message': f'{name} not found'}, 404 def create_one(self, payload): ''' Create an movie ''' resp, code = self.validate_schema(payload) if code != 200: return resp, code self.collection.insert_one(payload) return { 'message': f'Created movie: {payload}' }, 201 def update_one(self, name, payload): ''' update one movie by name ''' result = self.collection.find_one({'name': name}, {'_id': 0}) if result: self.collection.update_one({"name": name}, {"$set": payload}) return {'message': f'Updated {name}'}, 200 return { 'message': f'{name} not found' }, 404 def delete_one(self, name): ''' delete one movie by name ''' return { 'message': f'Delete {name}' }, 200 def validate_schema(self, payload): """ Validates application definiition against schema """ schema = load_json_schema('movie-schema.json') try: validate(payload, schema) except ValidationError as v_err: self.logger.warning('Schema validation error: %s', v_err) return { 'error': 'Failed schema validation', 'message': v_err.message, 'data': payload }, 422 except Exception as ex: # pylint: disable=broad-except self.logger.error('Unknown schema validation error: %s', ex) return { 'error': 'Unkown schema validation', 'message': ex, 'data': payload }, 400 return { 'message': 'Application defininion passed schema validation' }, 200
class Movies(): ''' Movies Class ''' def __init__(self): self.class_name = type(self).__name__ # Contact self.logger = logging.getLogger(self.class_name) self.collection_name = snake_case(self.class_name) self.collection = DBUtil().get_collection(self.collection_name) def get_all(self): ''' get all movies ''' self.logger.info(list(self.collection.find({}))) return { 'result': list( self.collection.find({}, {'_id': 0}) ) #'result': list(self.collection.find({}, {'_id': 0, 'genre': 1})) }, 200 def get_one(self, title): ''' get one movie by title ''' result = self.collection.find_one({'title': title}, {'_id': 0}) if result: return result, 200 return {'message': f'{title} not found'}, 404 def create_one(self, payload): ''' Create a movie ''' added_title = self.collection.find_one(payload) if added_title: return { 'message': f'Duplicate Error {payload} already in database' }, 409 self.collection.insert_one(payload) return { 'message': f'Created movie: {payload}', 'movieName': f'{payload["title"]}', 'movieGenre': f'{payload["genre"]}', }, 201 def update_one(self, title, payload): ''' update one movie by title ''' result = self.collection.find_one({'title': title}, {'_id': 0}) if result: self.collection.update_one({'title': title}, {'$set': payload}) return {'message': f'Updated {title}'}, 200 return {'message': f' {title} not found'}, 404 def delete_one(self, title): ''' delete one movie by title ''' result = self.collection.find_one({'title': title}, {'_id': 0}) if result: self.collection.delete_one(result) return {'message': f' {title}- successfully deleted from db'}, 200 return {'message': f' {title} not found'}, 404 def delete_many(self, title): ''' delete multiple movies of the same title by title ''' # result = self.collection.find({'title': title}, {'_id': 0}) #NO '_d'? use get_all logger? find_many? or get_all result = self.collection.find({'title': title}, {'_id': 0}) if result: self.collection.delete_many(result) return {'message': f'All titles by {title} have been deleted'}, 200 return {f'{title} not found'}, 404