def fixture_page(): fixs = Fixtures(app.config['dsn']) if request.method == 'GET': now = datetime.datetime.now() fixlist = fixs.get_fixturelist() return render_template('fixtures.html', FixtureList = fixlist, current_time=now.ctime()) elif 'fixtures_to_delete' in request.form: id_fixtures = request.form.getlist('fixtures_to_delete') for id_fixture in id_fixtures: fixs.delete_fixture(id_fixture) return redirect(url_for('fixture_page')) elif 'fixtures_to_add' in request.form: fixs.add_fixture(request.form['week']) return redirect(url_for('fixture_page')) elif 'fixtures_to_update' in request.form: fixs.update_fixture(request.form['id_fixture'], request.form['week']) return redirect(url_for('fixture_page')) elif 'fixtures_to_search' in request.form: searchlist = fixs.search_fixture(request.form['name']); now = datetime.datetime.now() fixlist = fixs.get_fixturelist() return render_template('fixtures.html', FixtureList = fixlist, SearchList = searchlist, current_time = now.ctime())
def app(request): config = copy(Config) config.TESTING = True config.APP_TYPE = 'admin' if 'admin_api' in request.keywords else 'public' app = create_app(config) if 'unit' in request.keywords: yield app else: fixtures = Fixtures(app) fixtures.setup() yield app fixtures.teardown()
def app(request): Config.TESTING = True app = create_app(Config) if 'unit' in request.keywords: # unit tests don't get data fixtures yield app else: # other tests need the test data set fixtures = Fixtures(app) fixtures.setup() yield app fixtures.teardown()
def main(): # initialize instances and print intro. #todo: make sure you only print intro (def initalize) once database = DatabaseSearcher() validate = Validation() option = Options() initialize() #first menu print_message("[1] Play a new game\n[2] Continue with a league") #get user input from first menu above users_pick = get_inputs("Enter choice: ", ['1', '2']) # starting new tournament if users_pick == '1': #create new instance of a tournament, using the database instance new_game = Tournament(database=database, new=True) #the type of sport to have the option to scale the software while True: type = new_game.get_type() if type in ['Soccer', 'UFC', 'Darts']: break else: print("Stay focused") if type == 'Soccer': #get all inputs from user new_game.get_tournament_name() new_game.get_total_players() new_game.get_rounds() new_game.set_players_name() new_game.set_total_games() #checks if user wants password in his tournament encryption = get_inputs("You want password protection [y/N] ", ['y', 'Y', 'N', 'n', ""]) if encryption.lower() == "y": new_game.get_password() # if form returns an emptylist, user doesn't want fixed teams # else it a a list of random teams to put in database form = new_game.get_form() if form == []: fixed = False else: fixed = True #from the instance, init total_games and game_counter variables for the playLOOP total_games = new_game.total_games game_counter = new_game.game_counter #database insertion, insert into tournament and insert into sport table tournament_id = database.create_new_tournament(name=new_game.name, total_players=new_game.total_players, total_rounds=new_game.total_rounds, password=new_game.password, namelist=new_game.players_list, fixed=fixed, rand_list=form) database.add_to_sport_table(type, database.get_newest_id('Tournament')) #todo: refactor this part #new instance of fixtures fixtures = Fixtures(database) #generate fixtures as list and then adding to dictionary the_fixtures = fixtures.generate_fixture_list(new_game.players_list, new_game.total_rounds) fixt_dixt = fixtures.insert_fixture_into_dict(the_fixtures) #insert into database database.insert_fixtures(the_fixtures, tournament_id) #assigning the fixt_dixt to the new_game instance self.fixtures new_game.fixtures = fixt_dixt #showing all fixtures before tournament starts fixtures.show_fixtures(tournament_id=database.get_newest_id('Tournament')) elif type == 'UFC': freeze_screen(1, "UFC not ready. Application closing ...") quit() elif type == 'Darts': freeze_screen(1, "Darts not ready. Application closing ...") quit() #below is playing a league that already exists elif users_pick == '2': freeze_screen(2, "Reading from database ...") if database.is_not_empty(): freeze_screen(2, "No leagues in the database") main() else: print_message("Available leagues:") database.print_available_leagues() #picking tournament tournament_id from a list while True: tournament_id = input("Enter the ID for the league you want to play? ") if database.get_tournament_by_id(tournament_id): name, players, rounds, game_counter = database.get_tournament_by_id(tournament_id) type = database.get_type(tournament_id) print("LeagueName:", name, "\nTotal Players: ", players, "\nTotal Rounds: ", rounds) players_dict = database.get_players_data(tournament_id=tournament_id) print(players_dict, "þetta er elísa") break #password protection while True: if database.is_password_protected(tournament_id=tournament_id) is True: password = input("Enter password: "******"Collecting data from database ...") break else: print_message("Incorrect password! Try again!") else: print("\n\nMaybe you should use a password next time.\n ") break #create players list #setting up new instance of tournament as new.game new_game = Tournament(database=database, tournament_id=tournament_id, type=type, name=name, rounds=rounds, players=players, game_counter=game_counter, players_list=None, new=False) #inserting into team instances new_game.set_players_name(players_dict=players_dict) print(LINES) print_message(f"WELCOME BACK TO {new_game.name}") print(LINES) #getting the total games for the play loop total_games = new_game.total_games # new instance of fixtures fixtures = Fixtures(database=database, tournament_id=new_game.tournament_id) #generate one list of fixtures from team instances in players list and excludes the day off the_fixtures = fixtures.generate_fixture_list(new_game.players_list, new_game.total_rounds) fixt_dixt = fixtures.insert_fixture_into_dict(the_fixtures, tournament_id=tournament_id) new_game.fixtures = fixt_dixt print(new_game.fixtures) fixtures.show_fixtures(tournament_id=tournament_id) else: exit("You don´t deserve us") #playing a game with new_game as instance of Tournament while game_counter < total_games: print(option.show()) the_option = option.get() if validate.limit(the_option, 1, 4) or the_option == "": if the_option == '': print(LINES) home, away = new_game.play_next_game(tournament_id=new_game.tournament_id, game_counter=new_game.game_counter) print("\n", LINES) # getting the score for the game while True: score = input("Enter results, two integers with space between: ") if validate.scores(score): score = score.split() a_game = Game(game_counter, score[0], score[1], home, away) score_list = [int(a_game.home_score), int(a_game.away_score)] fixtures.insert_score_to_fixture(score_list, game_counter) database.update_fixture_table(game_id=a_game.id, tournament_id=tournament_id, home_id=home.id, away_id=away.id, scores=score_list) a_game.handle_scores() #updating fixtures database.updated_played(tournament_id=tournament_id, game_id=game_counter) game_counter += 1 new_game.game_counter += 1 database.update_played_games_in_tournament_by_id(tournament_id=int(new_game.tournament_id)+1, played_games=game_counter) database.update_players_attributes(tournament_id=tournament_id, team_id=home.id, points=home.points, scored=home.scored_goals, conceded=home.conceded_goals, played=home.played_games) database.update_players_attributes(tournament_id= tournament_id, team_id=away.id, points=away.points, scored=away.scored_goals, conceded=away.conceded_goals, played=away.played_games) break elif the_option == '1': print(LINES) print(f" ~~~~~ {new_game.name} ~~~~~") print(f'\nYou are playing {new_game.total_rounds} rounds of the following games') print(LINES) #todo: print only unplayed games or games with scores fixtures.show_fixtures(tournament_id=tournament_id) print(LINES) freeze_screen(2) elif the_option == '2': print(new_game) freeze_screen(2) elif the_option == '3': print(option.show_stats()) stat_option = input("Pick your stat: ") if stat_option == '1': print(new_game.get_biggest_win()) elif stat_option == '2': print("Biggest loss(Birnir): X vs Y, 5 - 1.") elif stat_option == '3': print("Most games won in a row(Þórarinn): 6") else: freeze_screen(2, "NOT AN OPTION") elif the_option == '4': print("Writing out data...") time.sleep(2) print("All set! See you soon!") exit() # the end of the loop, it shows the league standings print(new_game) print("\n\n\n", LINES) print("CONGRATULATIONS\n", end=" ") #needs some fine tuning, get the tie, tiebreakers... print(new_game.get_winner()) print("\n\n", LINES)
if __name__ == '__main__': '''Container objects''' app.coaches = Coaches2(app) app.coaching = Coaching2(app) app.teams = Teams(app) app.players = Players(app) app.countries = Countries(app) app.leagues = Leagues(app) app.stadiums = Stadiums(app) app.officials = Officials(app) app.seasons = Seasons2(app) app.matches = Matches(app) app.statisticsTeam = StatisticsT(app) app.statisticsPlayer = StatisticsP(app) app.fixtures = Fixtures(app) app.squads = Squads(app) app.transfers = Transfers(app) VCAP_APP_PORT = os.getenv('VCAP_APP_PORT') if VCAP_APP_PORT is not None: port, debug = int(VCAP_APP_PORT), False else: port, debug = 5000, True VCAP_SERVICES = os.getenv('VCAP_SERVICES') if VCAP_SERVICES is not None: app.config['dsn'] = get_elephantsql_dsn(VCAP_SERVICES) else: app.config['dsn'] = """user='******' password='******' host='localhost' port=54321 dbname='itucsdb'"""
import yaml from fixtures import Fixtures, ColorGroups from colorLib import Colors, DynamicColors import copy scene = {'00_version': '0.1'} name = '' strobe = None led_bar_01 = Fixtures(dmx_adress = 1, dimmer_channel= 1, strobe_channel = 2, color_group_size = 6, number_of_color_groups = 12, color_groups_start_channel = 3) led_bar_02 = Fixtures(dmx_adress = 75, dimmer_channel= 1, strobe_channel = 2, color_group_size = 6, number_of_color_groups = 12, color_groups_start_channel = 3) fogger_01 = Fixtures(dmx_adress = 149, dimmer_channel= 2, strobe_channel = 4, color_group_size = 3, number_of_color_groups = 1, color_groups_start_channel = 5, fog_channel = 1) fogger_02 = Fixtures(dmx_adress = 156, dimmer_channel= 2, strobe_channel = 4, color_group_size = 3, number_of_color_groups = 1, color_groups_start_channel = 5, fog_channel = 1) #set overall faders faders = {led_bar_01.get_dimmer_adress(): {'value': 255, 'type': 'default'}, led_bar_02.get_dimmer_adress(): {'value': 255, 'type': 'default'}} def main(): '''static functions''' #strobe = 0 #color1 = Colors('red') #color2 = Colors('white_plain') #name = set_full_color(color1, strobe, left = True, right = True) #left and right can be specified optionally #name = set_cross_colors(color1, color2, strobe) #name = set_top_color(color1, strobe, left = True, right = True) #name = set_bottom_color(color1, strobe, left = True, right = True) #name = set_rise_color(color1, strobe, rise_number = 2, left = True, right = False) #name = set_seconds_colors(color1, color2, strobe)
def __init__(self, database, tournament_id=None, type=None, name=None, rounds=None, players=None, game_counter=None, players_list=None, new=False): self.database = database if tournament_id is None: self.tournament_id = self.database.get_newest_id('Tournament') else: self.tournament_id = tournament_id if type: self.type = type else: self.type = "" if name: self.name = name else: self.name = "" if rounds: self.total_rounds = rounds else: self.total_rounds = 0 if players: self.total_players = players else: self.total_players = 0 if game_counter: self.game_counter = game_counter else: self.game_counter = 0 if players_list: self.players_list = players_list for team in players_list: self.player = Team(team.name, team.points, team.played_games, team.scored_goals, team.conceded_goals) else: self.players_list = [] self.total_games = self.set_total_games() self.password = None self.options = Options() self.validate = Validation() if new: self.fixtures = Fixtures(database) else: self.fixtures = self.get_fixtures_from_db() self.randomlist = [ 'Real Madrid', 'Barcelona', 'Liverpool', 'Iceland', 'Brazil', 'PSG', '1 star', '2 star', 'Spain', '3 star', '4 star', 'Lowest star', 'Everton', 'Chelsea', 'Basel', 'Manchester City', 'IcelanderTeam', 'Manchester United', 'Arsenal', 'Leicester', 'Ajax', 'Atletico Madrid', 'Tottenham', 'Bayern Munchen', 'B. Dortmund', 'Juventus', 'Roma', 'Inter Milan', 'Colombia', 'England', 'Sweden', 'Scandinavia', 'Italy', 'Burnley', 'Sevilla' ]
class Tournament(): def __init__(self, database, tournament_id=None, type=None, name=None, rounds=None, players=None, game_counter=None, players_list=None, new=False): self.database = database if tournament_id is None: self.tournament_id = self.database.get_newest_id('Tournament') else: self.tournament_id = tournament_id if type: self.type = type else: self.type = "" if name: self.name = name else: self.name = "" if rounds: self.total_rounds = rounds else: self.total_rounds = 0 if players: self.total_players = players else: self.total_players = 0 if game_counter: self.game_counter = game_counter else: self.game_counter = 0 if players_list: self.players_list = players_list for team in players_list: self.player = Team(team.name, team.points, team.played_games, team.scored_goals, team.conceded_goals) else: self.players_list = [] self.total_games = self.set_total_games() self.password = None self.options = Options() self.validate = Validation() if new: self.fixtures = Fixtures(database) else: self.fixtures = self.get_fixtures_from_db() self.randomlist = [ 'Real Madrid', 'Barcelona', 'Liverpool', 'Iceland', 'Brazil', 'PSG', '1 star', '2 star', 'Spain', '3 star', '4 star', 'Lowest star', 'Everton', 'Chelsea', 'Basel', 'Manchester City', 'IcelanderTeam', 'Manchester United', 'Arsenal', 'Leicester', 'Ajax', 'Atletico Madrid', 'Tottenham', 'Bayern Munchen', 'B. Dortmund', 'Juventus', 'Roma', 'Inter Milan', 'Colombia', 'England', 'Sweden', 'Scandinavia', 'Italy', 'Burnley', 'Sevilla' ] def get_fixtures_from_db(self): """Reads the fixtures from database """ # database = DatabaseSearcher() dict = self.database.get_fixtures(self.tournament_id) return dict # return self.fixtures def get_password(self): """Gets the passwords from user and returns it""" #todo: implement hashing #todo: implement sending the password to email #todo: implement recover on password while True: password = getpass.getpass( prompt="Enter a easy password for later access: ") password2 = getpass.getpass(prompt="Repeat your password:"******"Remember: ", password) self.password = password return password else: print("Didn't match. Try again: ") def set_total_games(self): self.total_games = int(self.total_rounds) * int( self.__total_games_per_round__()) return self.total_games def get_type(self): """Gets the type of sport from menu options. Returns the type""" print(f"[1] Soccer/Fifa/PES\n[2] UFC\n[3] Darts") type = input().strip() if type in '123': if type == '1': self.type = 'Soccer' elif type == '2': self.type = 'UFC' elif type == '3': self.type = 'Darts' return self.type def get_form(self): """Gets the form the user. If the form is one random team throughout the league its assignes teams and returns the random_team list. Else it returns an empty list""" self.print_random_teamlist(6) play_random = input( f"You want to play with a fixed random team from our list [Y/n]: ") if play_random in "yY ": #Búa til lista með random liðum rand_teams = self.get_random_teams() # Prenta út hver er hvaða lið self.print_assigned_teams(self.players_list, rand_teams) # self.get_random_team() # commeentaði þetta út í bili. for i in range(self.total_players): # todo: capitalize rand_teams[i] in the string self.players_list[i].name += " " + "(" + rand_teams[ i] + ")" # Bæti hér við random liðinu fyrir aftan nafnið á spilaranum. return rand_teams else: return [] def random_every_game(self): """Offers the user to play with random team per round, returns random team if he wants, else returns False""" random_team_choice = input( "\nYou want us to choose random teams for every game? [Y/n]:") if random_team_choice in "Yy ": return random_team_choice # Returning this string if user wants random teams every game else: return False # Returning nothing if user chooses not to have random teams every game def get_tournament_name(self): """Returns the input of the tournament name""" while True: name = input("What is the name of your League: ").strip() if len(name) <= 30: self.name = name break else: print("Please try again. Max length is 30") return name def get_total_players(self): """Allows participants to enter number of competitors """ while True: players = input("How many players: ") if self.validate.integer(players): players = int(players) if self.validate.limit(players, min=2, max=10): self.total_players = players return int(players) def get_rounds(self): """Allows user to enter the number of rounds they want to play and returns that number""" while True: number = input("How many rounds you want to play? ") if self.validate.integer(number): if self.validate.limit(number, min=1, max=100): self.total_rounds = int(number) return int(number) def play_next_game(self, tournament_id, game_counter): """Plays the next game and returns the fixtures""" print("Next game is: \n") for game_number, value in self.fixtures.items(): #self.fixtures {game_number: [(a, b), [score]] home, away = value[0] #this is the score from the dict played = value[1] if played == []: self.database.updated_played(tournament_id, game_counter) print(home, "VS", away, end=" ") return home, away def set_players_name(self, players_dict=None): """Allows participants to enter names for themselves""" players = 0 if players_dict: for key, value in players_dict.items(): id = key for attr in value: name = attr[0] points = attr[1] scored = attr[2] conceded = attr[3] played = attr[4] new_team = Team(self.database, id=id, name=name, points=points, scored=scored, played=played, conceded=conceded) self.players_list.append(new_team) else: for i in range(int(self.total_players)): while players == i: team_name = input(f'Participant nr {players +1}: ') new_team = Team(database=self.database, id=players + 1, name=team_name) self.players_list.append(new_team) players += 1 def print_assigned_teams(self, players_list, rand_teams): """Prints assigned team for each player""" print("-- \nHere are the teams assigned for this league --\n") for i in range(self.total_players): print(f"{str(players_list[i]).capitalize()} -> {rand_teams[i]}\n") def get_random_teams(self): """Creates a list of random teams of size total players and returns it""" randlist = [] counter = 0 while counter < self.total_players: random_team = random.choice(self.randomlist) if random_team not in randlist: randlist.append(random_team.capitalize()) counter += 1 return randlist def __total_games_per_round__(self): """Returns total games per round""" return f"{round(((self.total_players*(self.total_players-1))/2))}" def __print_starting_info__(self): """Returns a starting info before the tournament starts""" retval = f'So {self.total_players} players are competing.\n' retval += f'You wanted to play {self.total_rounds} rounds.\n' retval += f'In total you will play {int(self.__total_games_per_round__())*int(self.total_rounds)} games' print(retval) return retval def print_random_teamlist(self, teams_in_one_line): """Prints all teams from randomlist""" retval = "" length = 0 for i in self.randomlist: length += len(i) if i == self.randomlist[-1]: retval += i elif length >= teams_in_one_line * 10: retval += "\n" length = 0 else: retval += f"{i}, " print(retval, "\n") #todo: implement a pretty print for the winner def get_winner(self): """Winner is decided by points but secondary decided on goal difference""" winner = self.players_list[0].name max_goal_diff = int(self.players_list[0].scored_goals) - int( self.players_list[0].conceded_goals) max_points = -1 goal_difference = False tied = [] for index, i in enumerate(self.players_list): curr_diff = int(i.scored_goals) - int(i.conceded_goals) if int(i.points) > max_points: max_goal_diff = int(i.points) winner = str(i.name) max_points = int(i.points) elif int(i.points) == max_points: if curr_diff > max_goal_diff: max_points = int(i.points) winner = str(i.name) max_goal_diff = curr_diff goal_difference = True elif max_goal_diff > curr_diff: continue else: winner = str(i.name) tied.append(winner) retval = "" if tied != []: retval += "TIED " for team in tied[0:-1]: retval += team + " -- " retval += tied[-1] elif goal_difference: retval = "\n\n\n CONGRATS \n\n" retval += f'{winner} with {str(max_goal_diff)} points, on GOAL DIFFERENCE!' else: retval = f'{winner} with {str(max_goal_diff)} points' return retval def get_biggest_win(self): max_difference = 0 max_string = "" for game_number, game in self.fixtures.items(): home, away = game[0] if (int(home.scored_goals) - int(away.scored_goals)) >= max_difference: max_difference = int(home.scored_goals) - int( away.scored_goals) max_string = f'{home.name} had {home.scored_goals} and {away.name} has {away.scored_goals}' return max_string def __str__(self): #todo: Refactor __str__ function for tournament print("\n" + PADDING + "\n\n") for i in range(MIDDLE - int(len(self.name) / 2)): print(" ", end="") print(f'{self.name}') for i in range(MIDDLE - int(len(self.name) / 2)): print(" ", end="") print("\n") print(PADDING, "\n") print("{:<27}{:}{:<10}{:}{:<10}" "{:}{:<11}{:}{:<6}{:}{:<6}".format("PLAYER", "", "PLAYED", "", "SCORED", "", "CONCEDED", "", "+/-", "", "POINTS")) print("{:<27}{:}{:<6}{:4}{:<7}{:<3}{:<3}{:<3}{:<3}{:<3}{:<3}".format( "----------", "", "------", "", "------", "", "--------", "", "---", "", "------")) sorted_x = self.multisort(list(self.players_list), (('points', True), ('name', False))) retval = "" for team in sorted_x: retval += "{:<27}".format(team.name).capitalize() retval += "{:3}".format(team.played_games).capitalize() retval += "{:10}".format(team.scored_goals).capitalize() retval += "{:11}".format(team.conceded_goals).capitalize() retval += "{:9}".format(team.scored_goals - team.conceded_goals).capitalize() retval += "{:7}\n".format(team.points).capitalize() return retval def multisort(self, xs, specs): for key, reverse in reversed(specs): xs.sort(key=operator.attrgetter(key), reverse=reverse) return xs
def handle_noargs(self, **options): f = Fixtures() f.load()