def __init__(self): """ We build the instance of the class. """ self.display_open_food_fact = Display() self.host = Glob.host self.user = Glob.user self.password = Glob.password self.database = Glob.database self.db_connect = mysql.connector.connect(host=self.host, user=self.user, password=self.password) self.cursor = self.db_connect.cursor() self.category_id = 0 self.cat_id = 0 self.food_id = "" self.food_name = "" self.food_url = "" self.food_shop = "" self.food_nutrition = "" self.substitute_id = 0 self.substitute_name = "" self.substitute_url = "" self.substitute_shop = "" self.substitute_nutrition = ""
def __init__(self): """ We build the instance of the class. """ self.database = MySQL() self.api_open_food_fact = Api() self.display_open_food_fact = Display()
def __init__(self): """ We build the instance of the class. """ self.database = MySQL() self.url = \ 'https://fr.openfoodfacts.org/langue/francais/categories.json' self.category_json = json.loads(requests.get(self.url).text) self.display_open_food_fact = Display()
def __init__(self, image, position, size): self.display = Display() # create surface self.image = image # get image size and position self.rect = pygame.Rect(position, size)
class Game: """ Main game loop """ def __init__(self): self.display = Display() self.select_team = SelectTeam() self.match_vars = MatchVariables() def run_sim(self): """ Simulator game loop """ # crowd audio pygame.mixer.music.stop() pygame.mixer.music.load('assets/audio/match/atm-normal.wav') pygame.mixer.music.play(-1) while self.match_vars.mins <= 90: rand_events = random.randint(1, 10) if self.match_vars.mins == 1: self.display.game_com("Kick Off", self.display.font_large) pygame.mixer.Sound('assets/audio/match/whistle.wav').play() time.sleep(3) if self.match_vars.mins == 45: self.display.game_com("Half Time", self.display.font_large) pygame.mixer.Sound('assets/audio/match/whistle.wav').play() time.sleep(5) pygame.mixer.Sound('assets/audio/match/whistle.wav').play() if rand_events == 1 or rand_events == 2: Chances().play() elif rand_events == 5 or rand_events == 6: Foul().play() else: Chances().idle() self.match_vars.update_mins() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() self.display.game_com("Full Time", self.display.font_large) pygame.mixer.Sound('assets/audio/match/whistle.wav').play() time.sleep(3)
def start_scene(): """ Runs the start screen """ from Menus.select_team import SelectTeam # placing the import in a func makes python import that module only when needed from Menus.button import Button from Display.display import Display select_team = SelectTeam() display = Display() # start scene audio pygame.mixer.music.load('assets/audio/menu/main_menu.wav') pygame.mixer.music.set_volume(0.3) pygame.mixer.music.play(-1) # loading main menu background main_menu_img = pygame.image.load( "assets/sprites/Backgrounds/main-menu.png").convert() # creating start button start_btn = Button( pygame.image.load("assets/sprites/Buttons/start-game.png").convert(), (410, 380), (200, 80)) while True: display.display_background(main_menu_img) display.display_text("Soccer Match Simulator 2020", display.font_title, (250, 300)) start_btn.draw() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # if start game is clicked move to SelectTeam class start_btn.event_handler(event, select_team.select_home) pygame.display.update()
def __init__(self): self.display = Display() self.select_team = SelectTeam() self.match_vars = MatchVariables()
class Api: """ This class is used for information retrieval in the API. """ def __init__(self): """ We build the instance of the class. """ self.database = MySQL() self.url = \ 'https://fr.openfoodfacts.org/langue/francais/categories.json' self.category_json = json.loads(requests.get(self.url).text) self.display_open_food_fact = Display() def request_category(self): """ Get category names from Open Food Facts. """ self.display_open_food_fact.loading_categories() for counter in range(Glob.nb_category): self.database.insert_data_category( self.category_json["tags"][counter]["name"]) self.display_open_food_fact.loading_point_category() self.display_open_food_fact.loading_completed_categories() def request_food(self): """ Get product information from Open Food Facts. """ "emplacement = 0" product_name = "" product_url = "" product_shop = "" product_nutrition = "" self.display_open_food_fact.loading_food() for category in range(Glob.nb_category + 1): category_choice_json = self.category_json["tags"][category - 1] answer_category_json = json.loads( requests.get(category_choice_json["url"] + ".json").text) for product in answer_category_json["products"]: try: product_name = product["product_name"] except KeyError: pass try: product_url = product["url"] except KeyError: pass try: product_shop = product["stores"] except KeyError: pass try: product_nutrition = product["nutrition_grades"] except KeyError: pass self.database.insert_data_product( category, product_name, product_url, product_shop, product_nutrition) self.display_open_food_fact.loading_point_food() self.display_open_food_fact.loading_completed_food()
class Chances(Players): """ Deals with a chance on goalnand setpieces for e.g a shot a pass to teammate a cross """ def __init__(self): super().__init__() self.match_vars = MatchVariables() self.display = Display() # SHOTS # play goal audio, crowd should be louder after goal and show image def goal(self, team, player): self.match_vars.increase_score(team, player) goal_scored = True pygame.mixer.Sound("assets/audio/match/goal.wav").play() self.display.draw_image(goal_img, (410, 280)) pygame.display.update() time.sleep(4) # play audio when miss def miss(self): pygame.mixer.Sound("assets/audio/match/miss.wav").play() def shot_on_target(self, player): goal = random.randint(1, 2) corner = random.randint(1, 2) if goal == 1: self.goal(self.attacking_team, player) else: self.display.game_com(f"{self.gk} saves!", self.display.font_small) if corner == 1: self.display.game_com( f"{self.gk} did not save the ball cleanly and it goes behind for a corner.", self.display.font_small) self.corner_kick() # if miss play audio def shot_off_target(self): r = random.randint(1, 10) msg = random.choice([ "The ball goes slightly over the bar! Great effort!", "That was nowhere near the goal!", "He hit the crossbar! Unlucky!" ]) self.miss() self.display.game_com(msg, self.display.font_small) def shoot(self, player): r = random.randint(1, 2) if r == 1: self.shot_on_target(player) else: self.shot_off_target() # PASS/CROSS def pass_ball(self): # through ball, low cross, high cross type_of_pass = random.randint(1, 10) volley_or_header = random.randint(1, 2) field = self.attacking_team[1:8] if self.player in field: field.remove(self.player) teammate = random.choice(field) if type_of_pass >= 1 and type_of_pass < 4: self.display.game_com( f"Great vision from {self.player} to find {teammate} with a pin-point through ball", self.display.font_small) self.display.game_com( f"{teammate} steadies himself and shoots!...", self.display.font_small) self.shoot(teammate) elif type_of_pass > 3 and type_of_pass < 7: self.display.game_com( f"{self.player} finds {teammate} with a low cross", self.display.font_small) self.display.game_com(f"{teammate} shoots!...", self.display.font_small) self.shoot(teammate) else: self.display.game_com( f"{self.player} finds {teammate} with a high cross", self.display.font_small) if volley_or_header == 1: self.display.game_com(f"{teammate} goes for the volley!", self.display.font_small) self.shoot(teammate) else: self.display.game_com(f"{teammate} heads it!", self.display.font_small) self.shoot(teammate) # DRIBBLE def dribble(self): event = random.randint(1, 2) is_pass = random.randint(1, 2) self.display.game_com(f"{self.player} dribbles with the ball...", self.display.font_small) if event == 1: self.display.game_com("Then, he attempts to pass to his teammate.", self.display.font_small) if is_pass: self.pass_ball() else: self.display.game_com(f"{self.defender} intercepts the ball", self.display.font_small) else: #solo-goal self.display.game_com( f"{self.player} takes it pass the defender. He's in the box!", self.display.font_small) self.shoot(self.player) # SETPIECES def freekick(self, team, set_piece_taker): """ This is done so python doesn't call Players init method again when it cannot find the variables thus creating a new random value """ self.attacking_team = team self.fk_taker = set_piece_taker pass_or_shoot = random.randint(1, 2) self.display.game_com( f"{self.attacking_team[0]} gets a freekick. {self.fk_taker} stands over it.", self.display.font_small) # pass if pass_or_shoot == 1: head = random.randint(1, 2) headed_goal = random.randint(1, 2) # any player except the goalkeeper is in the box box = self.attacking_team[1:10] # freekick taker is in box remove him if self.fk_taker in box: box.remove(self.fk_taker) teammate = random.choice(box) self.display.game_com( f"{self.fk_taker} tries to find the head of his teammate in the box", self.display.font_small) # ball lands on head if head == 1: self.display.game_com(f"{teammate} heads it!", self.display.font_small) # scores if headed_goal == 1: self.goal(self.attacking_team, teammate) else: self.display.game_com("He heads it over the bar.", self.display.font_small) # ball does not find teammmate else: self.display.game_com( "The ball flies over the heads of everyone in the box and goes out of play.", self.display.font_small) # Player shoots from freekick else: shoot = random.randint(1, 3) self.display.game_com(f"{self.fk_taker} goes for goal!...", self.display.font_small) # 33.33% chance he scores directly from freekick if shoot == 1: self.goal(self.attacking_team, self.fk_taker) else: self.miss() self.display.game_com("It goes over the bar! Great Effort.", self.display.font_small) def penalty(self, team, set_piece_taker, gk): self.attacking_team = team self.pk_taker = set_piece_taker self.gk = gk score = random.randint(1, 2) miss = random.choice( ["{} misses!".format(self.pk_taker), "{} saves!".format(self.gk)]) self.display.game_com("The referee points to the spot!", self.display.font_small) self.display.game_com( f"{self.pk_taker} places the ball and steps back...", self.display.font_small) self.display.game_com(f"{self.gk} gets ready to defend his goal", self.display.font_small) self.display.game_com(f"{self.pk_taker} runs up!...", self.display.font_small) self.display.game_com("He shoots!", self.display.font_small) if score == 1: self.goal(self.attacking_team, self.pk_taker) else: self.miss() self.display.game_com(miss, self.display.font_small) def corner_kick(self): success = random.randint(1, 2) event = random.randint(1, 10) goal = random.randint(1, 2) box = self.attacking_team[1:11] # excludes gk # remove corner kick taker if he is in the box if self.ck_taker in box: box.remove(self.ck_taker) teammate = random.choice(box) self.display.game_com( f"{self.attacking_team[0]} receives a corner. {self.ck_taker} is going to take it.", self.display.font_small) self.display.game_com(f"{self.ck_taker} whips it into the box!...", self.display.font_small) # successful corner attempt if success == 1: if event >= 1 and event <= 6: self.display.game_com(f"{teammate} jumps and head the ball!", self.display.font_small) if goal == 1: self.goal(self.attacking_team, teammate) else: self.miss() self.display.game_com("It's over the bar!", self.display.font_small) elif event > 6 and event <= 9: self.display.game_com(f"{teammate} tries a bicycle kick!...", self.display.font_small) if goal == 1: self.goal(self.attacking_team, teammate) else: self.miss() self.display.game_com( "Great effort but it goes slightly over the crossbar! ", self.display.font_small) else: if goal == 1: self.display.game_com( f"{self.ck_taker} goes for goal from the corner flag.", self.display.font_small) self.goal(self.attacking_team, self.ck_taker) else: self.display.game_com( "The ball fly over the heads of everyone in the box.", self.display.font_small) else: self.display.game_com( "The defender heads it clear. Good defending.", self.display.font_small) # when the two teams are struggling for possession/no chance for goal def idle(self): msg = random.choice([ "Both teams are struggling for possession...", f"{self.home_team[0]} and {self.away_team[0]} are battling it out together...", "We wait for a chance on goal as both teams are currently at a stalemate..." ]) self.display.game_com(msg, self.display.font_small) def play(self): # 50% chance player pass 30% chance player shoots 20% he dribbles dist = random.randint(20, 30) r = random.randint(1, 10) self.display.game_com(f"{self.attacking_team[0]} attacks...", self.display.font_small) if r >= 1 and r < 6: self.pass_ball() elif r >= 6 and r < 9: self.display.game_com( f"{self.player} goes for goal from {dist} yards out!", self.display.font_small) self.shoot(self.player) else: self.dribble()
def __init__(self): self.display = Display() self.background = pygame.image.load("assets/sprites/Backgrounds/background.png").convert()
class SelectTeam: # class variables for the team lists la_liga_team_names = ["REAL MADRID", "BARCELONA", "ATLETICO MADRID", "SEVILLA", "VALENCIA", "GETAFE"] bundesliga_team_names = ["BAYERN MUNICH", "DORTMUND", "RB LIEPZIG", "LEVERKUSEN", "WOLFSBURG", "FRANKFURT"] premier_team_names = ["MAN. CITY", "LIVERPOOL", "CHELSEA", "TOTTENHAM", "ARSENAL", "MAN. UNITED"] ligue1_team_names = ["PSG"] serieA_team_names = ["JUVENTUS", "INTER MILAN", "AC MILAN", "AS ROMA", "NAPOLI", "LAZIO"] # is both a home and away team selected home_selected = False all_teams = la_liga_team_names + bundesliga_team_names + premier_team_names + ligue1_team_names + serieA_team_names """ list format by index 0 = team name 1-3 = attackers 4-6 = midfielders 7-10 = defenders 11 = goalkeeper 12-14 = substitutes (3 substitutes) 15 = freekick taker 16 = cornerkick taker 17 = penalty taker """ la_liga_teams = [["REAL MADRID", "E. Hazard", "K. Benzema", "Vinicius Jr.", "T. Kroos", "Casemiro", "L. Modric", "Marcelo", "Varane", "S. Ramos", "D. Carvajal", "T. Courtois", "M. Asensio", "L. Vazquez", "G. Bale", "S. Ramos", "L. Modric", "S. Ramos"], ["BARCELONA", "L. Messi", "L. Suarez", "A. Griezmann", "F. De Jong", "S. Busquets", "Vidal", "N. Semedo", "Umtiti", "Pique", "J. Alba", "M. ter Stegen", "Pjanic", "O. Dembele", "A. Fati", "L. Messi", "L. Messi", "L. Suarez"], ["ATLETICO MADRID", "J. Felix", "Morata", "Saul", "T. Lemar", "Correa", "Koke", "Lodi", "Hermoso", "Savic", "Trippier", "Jan Oblak", "T. Partey", "N. Llorente", "Diego Costa", "A. Griezmann", "Koke", "A. Griezmann"], ["VALENCIA", "M. Gomez", "Gameiro", "Mina", "Goncalo Guedes", "Kondogbia", "Parejo", "Gaya", "Gabriel", "Garay", "D. Wass", "J. Cillessen", "Soler", "D. Cheryshev", "Rodrigo", "Parejo", "Parejo", "Parejo"], ["GETAFE", "J. Mata", "J. Molina", "Angel Rodriguez", "M. Cucurella", "N. Maksimovic", "Jason", "Olivera", "Timor", "Djene", "Cabaco", "D. Soria", "Duro", "F. Portillo", "A. Ndiaye", "N/A", "N/A", "N/A"], ["SEVILLA", "L. de Jong", "El Haddadi", "Torres", "Jordan", "Fernando R.", "Banega", "Navas", "Kounde", "Diego Carlos", "S. Reguilon", "T. Vaclik", "Y. En-Nesyri", "Suso", "Sergi Gomez", "N/A", "N/A", "N/A"] ] serieA_teams = [["AC MILAN", "H. Calhanoglu", "Z. Ibrahimovic", "A. Rebic", "F. Kessie", "L. Biglia", "G. Bonaventura", "T. Hernandez", "M. Musacchio", "A. Romagnoli", "A. Conti", "G. Donnarumma", "S. Castillejo", "R. Krunic", "L. Duarte", "M/A", "N/A", "Z. Ibrahimovic"], ["INTER MILAN", "L. Martinez", "R. Lukaku", "A. Sanchez", "A. Candreva", "C. Eriksen", "M. Vecino", "D. Godin", "M. Skriniar", "S. de Vrij", "D. D'Ambrosio", "S. Handovic", "M. Brozovic", "N. Barella", "A. Bastoni", "N/A", "N/A", "R. Lukaku"], ["JUVENTUS", "Cristiano Ronaldo", "Higuain", "P. Dybala", "B. Matuidi", "R. Bentacur", "A. Ramsey", "A. Sandro", "Chiellini", "Bonucci", "Danilo", "W. Szczesny", "Douglas Costa", "M. De Ligt", "Arthur", "Cristiano Ronaldo", "P. Dybala", "Cristiano Ronaldo"], ["NAPOLI", "D. Mertens", "K. Insigne", "H. Lozano", "F. Ruiz", "P. Zielinski", "Allan", "Mario Rui", "K. Koulibaly", "Albiol", "Manolas", "D. Ospina", "A. Milik", "Hysaj", "Callejon", "N/A", "Allan", "D. Mertens"], ["AS ROMA", "J. Kluivert", "Dzeko", "Schick", "Under", "N. Zaniolo", "Florenzi", "A. Kolarov", "F. Fazio", "C. Smalling", "Santon", "R. Olsen", "Pastore", "Perotti", "N. Kalinic", "A. Kolarov", "A. Kolarov", "A. Kolarov"], ["LAZIO", "F. Caicedo", "C. Immobile", "J. Correa", "Luis Alberto", "S. Milinkovic-Savic", "Jony", "J. Lukaku", "L. Felipe", "F. Acerbi", "Radu", "T. Strakosha", "L. Leiva", "M. Parolo", "M. Lazzari", "N/A", "N/A", "C. Immobile"]] bundesliga_teams = [["BAYERN MUNICH", "L. Sane", "R. Lewandowski", "S. Gnabry", "P. Coutinho", "J. Martinez", "J. Kimmich", "D. Alaba", "L. Hernandez", "N. Sule", "B. Pavard", "M. Neuer", "C. Tolisso", "I. Perisic", "Thiago", "D. Alaba", "D. Alaba", "R. Lewandowski"], ["DORTMUND", "T. Hazard", "E. Haaland", "J. Sancho", "M. Reus", "E. Can", "J. Brandt", "N. Schulz", "M. Hummels", "M. Akanji", "T. Meunier", "R. Burki", "A. Witsel", "T. Delaney", "R. Guerreiro", "J. Sancho", "M. Reus", "E. Haaland"], ["LEVERKUSEN", "L. Bailey", "K. Volland", "M. Diaby", "K. Havertz", "K. Demirbay", "E. Palacios", "Wendell", "S. Bender", "J. Tah", "M. Weiser", "L. Hradecky", "L. Alario", "Paulinho", "N. Amiri", "L. Bailey", "N/A", "K. Volland"], ["RB LIEPZIG", "Y. Poulsen", "J. Augustin", "H. Hwang", "D. Olmo", "K. Kampl", "M. Sabitzer", "M. Halstenberg", "W. Orban", "D. Upamecano", "B. Henrichs", "P. Gulacsi", "O. Bias", "A. Lookman", "F. Hartmann", "N/A", "N/A", "N/A"], ["WOLFSBURG", "J. Brekalo", "W. Weghorst", "R. Steffen", "Y. Gerhardt", "J. Guilavogui", "M. Arnold", "J. Roussillon", "M. Pongracic", "J. Brooks", "William", "K. Casteels", "X. Schlager", "F. Claus", "D. Ginczek", "N/A", "N/A", "W. Weghorst"], ["FRANKFURT", "B. Dost", "A. Silva", "G. Paciencia", "F. Kostic", "D. Kamada", "D. Sow", "T. Chandler", "D. Abraham", "M. Hinteregger", "E. Durm", "K. Trapp", "D. Joveljic", "M. Gacinovic", "S. Rode", "N/A", "N/A", "N/A"]] ligue1_teams = [["PSG", "Neymar", "M. Icardi", "K. Mbappe", "A. Di Maria", "I. Gueye", "M. Veratti", "L. Kurzawa", "T. Silva", "P. Kimpembe", "T. Kehrer", "K. Navas", "E. Cavani", "J. Draxler", "P. Sarabia", "Neymar", "Neymar", "M. Icardi"]] premier_teams = [["MAN. CITY", "R. Sterling", "S. Aguero", "R. Mahrez", "B. Silva", "Fernandinho", "K. De Bruyne", "B. Mendy", "N. Otamendi", "A. Laporte", "K. Walker", "Ederson", "D. Silva", "O. Zinchenko", "Rodri", "K. De Bruyne", "K. De Bruyne", "S. Aguero"], ["MAN. UNITED", "A. Martial", "M. Rashford", "D. James", "B. Fernandes", "P. Pogba", "S. McTominay", "L. Shaw", "E. Bailly", "V. Lindelof", "A. Wan-Bissaka", "D. De Gea", "Fred", "J. Mata", "M. Rojo", "M. Rashford", "P. Pogba", "M. Rashford"], ["LIVERPOOL", "S. Mane", "R. Firmino", "M. Salah", "J. Milner", "Fabinho", "J. Henderson", "Robertson", "J. Matip", "V. Van Dijk", "T. Alexander-Arnold", "Alisson", "J. Gomez", "G. Wijnaldum", "D. Origi", "R. Firminho", "J. Milner", "J. Milner"], ["ARSENAL", "N. Pepe", "P. Aubameyang", "A. Lacazette", "M. Ozil", "D. Ceballos", "M. Guendouzi", "S. Kolasinac", "D. Luiz", "Sokratis", "H. Bellerin", "B. Leno", "L. Torreira", "E. Nketiah", "S. Mustafi", "P. Aubamenyang", "M. Ozil", "P. Aubameyang"], ["CHELSEA", "C. Pulisic", "T. Werner", "H. Ziyech", "M. Kovacic", "N. Kante", "Jorginho", "Emerson", "K. Zouma", "A. Rudiger", "C. Azpilicueta", "Kepa", "Willian", "Pedro", "T. Abraham", "N/A", "N. Kante", "Jorginho"], ["TOTTENHAM", "H. Son", "H. Kane", "L. Moura", "D. Alli", "G. Lo Ceslo", "M. Sissoko", "B. Davis", "T. Alderweireld", "J. Vertonghen", "S. Aurier", "H. LLoris", "E. Lamela", "H. Winks", "T. Ndombele", "N/A", "N/A", "H. Kane"]] teams_dict = {} # matching team name to list with lineup in key-value relationship # key - team name, value - lineup list for team in all_teams: for i in range(6): if la_liga_teams[i][0] == team: teams_dict[team] = la_liga_teams[i] if bundesliga_teams[i][0] == team: teams_dict[team] = bundesliga_teams[i] if serieA_teams[i][0] == team: teams_dict[team] = serieA_teams[i] # only one team P.S.G if ligue1_teams[0][0] == team: teams_dict[team] = ligue1_teams[0] if premier_teams[i][0] == team: teams_dict[team] = premier_teams[i] # home and away team vars home = " " away = " " # home team and away team list with name of players home_team = [] away_team = [] def __init__(self): self.display = Display() self.background = pygame.image.load("assets/sprites/Backgrounds/background.png").convert() def la_liga(self): self.display_in_grid(self.la_liga_team_names) def bundesliga(self): self.display_in_grid(self.bundesliga_team_names) def premier(self): self.display_in_grid(self.premier_team_names) def ligue1(self): self.display_in_grid(self.ligue1_team_names) def serieA(self): self.display_in_grid(self.serieA_team_names) def display_leagues(self, team): """ Show flag buttons for each league """ # load the flag images la_liga = Button(pygame.image.load("assets/sprites/Buttons/Flags/spain.png").convert(), (100, 200), (120, 100)) premier = Button(pygame.image.load("assets/sprites/Buttons/Flags/england.png").convert(), (240, 200), (120, 100)) bundesliga = Button(pygame.image.load("assets/sprites/Buttons/Flags/germany.png").convert(), (380, 200), (120, 100)) ligue1 = Button(pygame.image.load("assets/sprites/Buttons/Flags/france.png").convert(), (520, 200), (120, 100)) serieA = Button(pygame.image.load("assets/sprites/Buttons/Flags/italy.png").convert(), (660, 200), (120, 100)) while True: # displaying the background self.display.display_background(self.background) self.display.display_text(f"Select {team} team league: ", self.display.font_large, (100, 100)) # drawing the flags la_liga.draw() premier.draw() bundesliga.draw() ligue1.draw() serieA.draw() # when flag clicked for event in pygame.event.get(): la_liga.event_handler(event, self.la_liga) bundesliga.event_handler(event, self.bundesliga) premier.event_handler(event, self.premier) ligue1.event_handler(event, self.ligue1) serieA.event_handler(event, self.serieA) if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() def display_in_grid(self, team_list): """ List all of the teams in a given league """ text = [] # The screen that is now showing team_screen = "home" if home_screen else "away" while True: self.display.display_background(self.background) COLUMN_WIDTH = 200 ROW_WIDTH = 50 x = 100 y = 200 # number of teams in row row = 0 # index of team i = 0 # displaying teams in 3 x 2 grid for team in team_list: # when 3 teams in row move to new column if row == 3: x = 100 y += ROW_WIDTH self.display.display_text(team, self.display.font_small, (x, y)) text.append(self.display.display_text(team, self.display.font_small, (x, y))) x += COLUMN_WIDTH row += 1 i += 1 self.display.display_text(f"Press Spacebar to return to select {team_screen} team league screen", self.display.font_small, (200, 500)) for event in pygame.event.get(): for tup in text: # checking if they were clicked if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: # tuple(text, text_rect) if tup[1].collidepoint(event.pos): if self.home_selected: # setting away team SelectTeam.away = tup[0] SelectTeam.away_team = self.teams_dict[SelectTeam.away] Lineups(SelectTeam.home_team, SelectTeam.away_team).display_lineups() else: # setting home team self.home_selected = True SelectTeam.home = tup[0] SelectTeam.home_team = self.teams_dict[SelectTeam.home] self.select_away() # if spacebar is clicked return to previous menu if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if home_screen: self.select_home() else: self.select_away() if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() # select home team def select_home(self): global home_screen home_screen = True self.display_leagues("home") # select away team def select_away(self): global home_screen, away_screen away_screen = True home_screen = False self.display_leagues("away")
class Main: """ This class is used for the application menu and the different requests. """ def __init__(self): """ We build the instance of the class. """ self.database = MySQL() self.api_open_food_fact = Api() self.display_open_food_fact = Display() def interaction_user_connect(self): """ This method allows you to create the database or to connect it. """ choice_connection = 1 while choice_connection: choice = self.display_open_food_fact.menu_connection() if choice == "1": self.database.create_database() self.database.connecting_db() self.api_open_food_fact.request_category() self.api_open_food_fact.request_food() self.interaction_user() break elif choice == "2": self.database.connecting_db() self.interaction_user() break elif choice == "3": choice_connection = 0 else: self.display_open_food_fact.menu_error() def interaction_user(self): """ This method allows you to search for the products to substitutes and the preferred substitutes. """ choice_menu = 1 while choice_menu: choice = self.display_open_food_fact.menu() if choice == "1": """Infinite loops are for repeating the question in case of character that is not a number.""" while True: """Loop for category choice.""" self.display_open_food_fact.category() self.database.select_category() try: choice_category = \ self.display_open_food_fact.choice_category() if choice_category[0] <= Glob.nb_category: break else: self.display_open_food_fact.choice_error() except ValueError: self.display_open_food_fact.choice_error() while True: """Loop for product choice.""" try: self.display_open_food_fact.product() self.database.select_cat_food(choice_category) choice_product = self.\ display_open_food_fact.choice_product() self.database.select_food(choice_product) break except ValueError: self.display_open_food_fact.choice_error() while True: """Loop of the proposal of the substitute and the saving of this one.""" self.display_open_food_fact.suggested_substitute() self.database.select_substitute(choice_category) saved = self.display_open_food_fact.substitute_saved() if saved == "1": self.database.insert_substitute_save() break elif saved == "2": break else: self.display_open_food_fact\ .suggested_substitute_error() elif choice == "2": self.substitutes_save() elif choice == "3": self.database.data_close() choice_menu = 0 else: self.display_open_food_fact.menu_error() def substitutes_save(self): """ This method allows you to see the favorite substitutes and delete them. """ substituted = 1 while substituted: choice = self.display_open_food_fact.menu_favored() if choice == "1": """Infinite loops are for repeating the question in case of character that is not a number.""" self.display_open_food_fact.favored_substitute() while True: """Loop to see the substitutes save.""" try: self.database.\ select_substitute_save() self.display_open_food_fact.\ favored_information_substitute() choice_substituted = self.\ display_open_food_fact.choice_favored_substitute() self.database.\ information_substitute_save(choice_substituted) break except ValueError: self.display_open_food_fact.choice_error() elif choice == "2": while True: """Loop to remove substituted backup.""" try: self.display_open_food_fact.delete_substitute() self.database.select_substitute_save() choice_delete = self.\ display_open_food_fact.choice_delete_substitute() self.database.delete_substitute(choice_delete) break except ValueError: self.display_open_food_fact.choice_error() elif choice == "3": substituted = 0 self.interaction_user() else: self.display_open_food_fact.menu_error()
def __init__(self): super().__init__() self.match_vars = MatchVariables() self.display = Display()
class Lineups(): def __init__(self, home_team, away_team): self.display = Display() self.home_team = home_team self.away_team = away_team def display_players(self): # lineup boxs image lineup_box = pygame.image.load( "assets/sprites/Backgrounds/lineup.png").convert() # Box for home team self.display.draw_image(lineup_box, (20, 20)) # Box for away team self.display.draw_image(lineup_box, (600, 20)) home_team = self.home_team away_team = self.away_team # vars to postion text # home and away team hy = 24 ay = 24 # Space between names SPACE = 40 # Displaying home team name self.display.display_text(home_team[0], self.display.font_small, (22, 22)) # Display names of players on home team for i in range(1, 12): hy += SPACE self.display.display_text(home_team[i], self.display.font_small, (22, hy)) # Displaying away team name self.display.display_text(away_team[0], self.display.font_small, (602, 22)) # Display names of players on away team for i in range(1, 12): ay += SPACE self.display.display_text(away_team[i], self.display.font_small, (602, ay)) def display_lineups(self): # menu audio pygame.mixer.music.stop() # stopping main menu audio before playing pygame.mixer.music.load("assets/audio/match/lineup.wav") pygame.mixer.music.play(-1) #loading background field_bkg = pygame.image.load( "assets/sprites/Backgrounds/play-screen.png").convert() run = True while run: self.display.display_background(field_bkg) self.display_players() self.display.display_text("Press Spacebar to continue", self.display.font_small, (400, -5)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # if users presses spacebar start simulator if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: # run sims from Match.game import Game Game().run_sim() self.display.scoresheet() run = False pygame.display.update()
class MySQL: """ This class is used for the creation, the connection, the insertion, the selection of different information in the database. """ def __init__(self): """ We build the instance of the class. """ self.display_open_food_fact = Display() self.host = Glob.host self.user = Glob.user self.password = Glob.password self.database = Glob.database self.db_connect = mysql.connector.connect(host=self.host, user=self.user, password=self.password) self.cursor = self.db_connect.cursor() self.category_id = 0 self.cat_id = 0 self.food_id = "" self.food_name = "" self.food_url = "" self.food_shop = "" self.food_nutrition = "" self.substitute_id = 0 self.substitute_name = "" self.substitute_url = "" self.substitute_shop = "" self.substitute_nutrition = "" def create_database(self): """ We are creating the database. """ self.cursor.execute("DROP DATABASE IF EXISTS `database`;") self.cursor.execute("CREATE DATABASE `database`;") self.cursor.execute("USE `database`;") self.cursor.execute("CREATE TABLE Category (\ category_id INT AUTO_INCREMENT NOT NULL,\ name VARCHAR(250) NOT NULL,\ PRIMARY KEY (category_id));") self.cursor.execute("CREATE TABLE Food (\ food_id INT AUTO_INCREMENT NOT NULL,\ cat_id INT NOT NULL,\ food_name VARCHAR(250) NOT NULL,\ food_url VARCHAR(300) NOT NULL,\ food_shop VARCHAR(300),\ food_nutrition CHAR(1),\ PRIMARY KEY (food_id, cat_id));") self.cursor.execute("CREATE TABLE Substitute (\ substitute_id INT AUTO_INCREMENT NOT NULL,\ substitute_name VARCHAR(250) NOT NULL,\ substitute_url VARCHAR(300) NOT NULL,\ substitute_shop VARCHAR(300),\ substitute_nutrition CHAR(1),\ PRIMARY KEY (substitute_id));") self.display_open_food_fact.create_database() def connecting_db(self): """ Connection to the database. """ self.db_connect = mysql.connector.connect(host=self.host, user=self.user, password=self.password, database=self.database) self.display_open_food_fact.connection_database() def insert_data_category(self, p_category_name): """ Insertion of category information into the database. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") sql = "INSERT INTO Category (category_id, name) VALUES (%s, %s);" val = (self.cursor.lastrowid, p_category_name) self.cursor.execute(sql, val) self.db_connect.commit() def insert_data_product(self, p_category, p_product_name, p_product_url, p_product_shop, p_product_nutrition): """ Insertion of product information into the database. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") sql = "INSERT INTO Food\ (food_id, cat_id, food_name, food_url, food_shop, food_nutrition)\ VALUES (%s, %s, %s, %s, %s, %s);" val = (self.cursor.lastrowid, p_category, p_product_name, p_product_url, p_product_shop, p_product_nutrition) self.cursor.execute(sql, val) self.db_connect.commit() def select_category(self): """ We select the category_id column from the Category table to retrieve the database information. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") select_category = "SELECT category_id, name FROM Category;" self.cursor.execute(select_category) for self.category_id, self.name in self.cursor: self.display_open_food_fact.select_category_db( self.category_id, self.name) def select_cat_food(self, p_choice_category): """ In this method we select different columns from the Food table. But we also make a join between two tables. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") select_cat_food = 'SELECT food_id, food_name FROM Food\ INNER JOIN Category\ ON Category.category_id = Food.cat_id\ WHERE Category.category_id = %s;' self.cursor.execute(select_cat_food, p_choice_category) for self.food_id, self.food_name in self.cursor: self.display_open_food_fact.select_cat_food_db( self.food_id, self.food_name) def select_food(self, p_choice_product): """ In this method we select different columns from the Food table. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") select_food = 'SELECT food_name, food_url, food_shop,' \ ' UPPER(food_nutrition) AS food_nutrition_upper FROM Food\ WHERE Food.food_id = %s;' self.cursor.execute(select_food, p_choice_product) for self.food_name, self.food_url, self.food_shop, self.food_nutrition\ in self.cursor: self.display_open_food_fact.select_food_db(self.food_name, self.food_url, self.food_shop, self.food_nutrition) def select_substitute(self, p_choice_category): """ In this method we select different columns from the Food table. But we also make a join between two tables. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") id_substitute = "1" # 102 == The letter "f" in ASCII nutri_substitute = 102 substitute = 'SELECT food_id, UPPER(food_nutrition) ' \ 'AS food_nutrition_upper FROM Food\ INNER JOIN Category\ ON Category.category_id = Food.cat_id\ WHERE Category.category_id = %s;' self.cursor.execute(substitute, p_choice_category) for self.food_id, self.food_nutrition in self.cursor: "print(self.food_id, ord(self.food_nutrition))" for increment in range(5): """print("increment" + str(increment + 97))""" if ord(self.food_nutrition) <= increment + 97 and\ ord(self.food_nutrition) < nutri_substitute: id_substitute = self.food_id nutri_substitute = ord(self.food_nutrition) select_substitute = 'SELECT food_name, food_url, food_shop, ' \ 'UPPER(food_nutrition) AS food_nutrition_upper FROM Food\ WHERE Food.food_id = %s;' self.cursor.execute(select_substitute, (int(id_substitute), )) for self.food_name, self.food_url, self.food_shop, self.food_nutrition\ in self.cursor: self.display_open_food_fact.select_substitute_db( self.food_name, self.food_url, self.food_shop, self.food_nutrition) def insert_substitute_save(self): """ Insertion of product information into the database. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") sql = "INSERT INTO Substitute " \ "(substitute_id, substitute_name, substitute_url," \ " substitute_shop, substitute_nutrition)\ VALUES (%s, %s, %s, %s, %s)" val = (self.cursor.lastrowid, self.food_name, self.food_url, self.food_shop, self.food_nutrition) self.cursor.execute(sql, val) self.db_connect.commit() def select_substitute_save(self): """ In this method, we save the selected substitutes. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") select_substitute_save =\ 'SELECT substitute_id, substitute_name FROM Substitute' self.cursor.execute(select_substitute_save) for self.substitute_id, self.substitute_name in self.cursor: self.display_open_food_fact.select_substitute_save_db( self.substitute_id, self.substitute_name) def information_substitute_save(self, p_choice_substituted): """ In this method, we display the information of the substitutes. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") information_substitute_save = 'SELECT substitute_name,\ substitute_url, substitute_shop, substitute_nutrition FROM Substitute\ WHERE Substitute.substitute_id = %s;' self.cursor.execute(information_substitute_save, p_choice_substituted) for self.substitute_name, self.substitute_url, \ self.substitute_shop, self.substitute_nutrition\ in self.cursor: self.display_open_food_fact.information_substitute_save_db( self.substitute_name, self.substitute_url, self.substitute_shop, self.substitute_nutrition) def delete_substitute(self, p_choice_delete): """ In this method, we remove the substitutes save. """ self.cursor = self.db_connect.cursor() self.cursor.execute("USE `database`;") delete_substitute = 'DELETE FROM Substitute\ WHERE Substitute.substitute_id = %s;' self.cursor.execute(delete_substitute, p_choice_delete) self.display_open_food_fact.delete_substitute_db(p_choice_delete) def data_close(self): """ In this method, we close the database. """ self.cursor = self.db_connect.cursor() self.db_connect.commit() self.cursor.close()
def __init__(self, home_team, away_team): self.display = Display() self.home_team = home_team self.away_team = away_team
class Foul(Players): """ Deals with fouls events """ def __init__(self): super().__init__() self.display = Display() self.match_vars = MatchVariables() # substitute player if injured def injury(self): player_index = 0 # selecting index of substitute sub_index = random.randint(12, 14) substitute = self.attacking_team[sub_index] # checking if substitute has already been used while substitute is None: sub_index = random.randint(12, 14) substitute = self.attacking_team[sub_index] self.display.game_com( f"{self.player} is writhing on the pitch in pain!", self.display.font_small) self.display.game_com(f"{substitute} replaces {self.player}", self.display.font_small) # getting the injuired player's index in the first eleven for i in range(1, 11): if self.attacking_team[i] == self.player: player_index = i # swapping injuired player for subsitute self.attacking_team[player_index] = substitute # removing substitute's name from bench as he is now on the field self.attacking_team[sub_index] = None def red_card(self): player_index = 0 injury = random.randint(1, 2) self.display.game_com( f"Red Card! {self.defender} receives a red card for his nasty tackle on {self.player}", self.display.font_small) # adding to list of players who received a red self.match_vars.red.append(self.defender) # Checking if player recieved a yellow before and removing him from yellow if self.defender in self.match_vars.yellow: self.match_vars.yellow.remove(self.defender) # getting the defender's index for i in range(1, 11): if self.opposing_team[i] == self.defender: player_index = i # removing defender from team self.opposing_team[player_index] = None # checking if is name was set as a set-piece taker # freekick if self.defender == self.opposing_team[15]: self.opposing_team[15] = "N/A" # corner if self.defender == self.opposing_team[16]: self.opposing_team[16] = "N/A" # pk if self.defender == self.opposing_team[17]: self.opposing_team[17] if injury == 1: self.injury() def yellow_card(self): self.display.game_com("Yellow card!", self.display.font_small) # if player already recieved yellow he should recieve a red card if self.defender in self.match_vars.yellow: self.display.game_com("It's his second yellow!", self.display.font_small) self.match_vars.yellow.remove(self.defender) self.red_card() Chances().freekick(self.attacking_team, self.fk_taker) else: self.match_vars.yellow.append(self.defender) self.display.game_com( f"{self.defender} will have to be careful now.", self.display.font_small) def play(self): event = random.randint(1, 10) in_box = random.randint(1, 10) # 0% chance player is tripped in box if in_box == 10: self.display.game_com( f"{self.defender} trips {self.player} in the box!", self.display.font_small) # 50-50 chance of a yellow or red if event == 1: self.yellow_card() else: self.red_card() Chances().penalty(self.attacking_team, self.pk_taker, self.gk) # 90% chance player is fouled outside of the box else: self.display.game_com( f"{self.defender} tackles {self.player} roughly.", self.display.font_small) self.display.game_com(f"The referee approaches the players...", self.display.font_small) # 40% chance player only gets a warning if event < 5: self.display.game_com( f"The referee gives {self.defender} a warning.", self.display.font_small) Chances().freekick(self.attacking_team, self.fk_taker) # 50% chance player recieves a yellow card elif event >= 5 and event < 10: self.yellow_card() Chances().freekick(self.attacking_team, self.fk_taker) # 10% chance player recieves a red else: self.red_card() Chances().freekick(self.attacking_team, self.fk_taker)