-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
189 lines (156 loc) · 6.28 KB
/
app.py
File metadata and controls
189 lines (156 loc) · 6.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
from flask import Flask, render_template, redirect, request, session, url_for
from difflib import SequenceMatcher
import requests
import time
import json
import os
import sqlite3
app = Flask(__name__)
app.secret_key = "Cocktail"
#------------------------------------------------------------------------------------------------------
# ---------------------------------------------- ROUTES -----------------------------------------------
#------------------------------------------------------------------------------------------------------
@app.route("/")
def home():
return render_template("homepage.html")
@app.route("/about")
def about():
return render_template("aboutUs.html")
# Route dynamique qui gère les URLs /facile, /moyen, /difficile
@app.route("/<difficulty>", methods=["GET", "POST"])
def play(difficulty):
if difficulty not in ['facile', 'moyen', 'difficile']:
return redirect(url_for('home'))
if "cocktail" not in session:
nom, img, ingredients, nbmIngredient = getRandomCocktailFromAPI()
session["cocktail"] = {
"nom": nom,
"img": img,
"ingredients": ingredients,
"nbmIngredient": nbmIngredient,
"start_time": time.time()
}
session["difficulty"] = difficulty
nom = session["cocktail"]["nom"]
img = session["cocktail"]["img"]
ingredients = session["cocktail"]["ingredients"]
nbmIngredient = session["cocktail"]["nbmIngredient"]
print(ingredients)
message = None
if request.method == "POST" and "user_input" in request.form:
user_input = request.form.get("user_input").strip()
len_before = len(ingredients)
ingredients = getValideIngredient(user_input, ingredients)
if len(ingredients) < len_before:
message = {"type": "success", "text": f"Bravo ! {user_input} est correct."}
else:
message = {"type": "danger", "text": f"Dommage, {user_input} n'est pas dans la liste."}
session["cocktail"]["ingredients"] = ingredients
session.modified = True
if len(ingredients) == 0:
end_time = time.time()
time_taken = end_time - session["cocktail"]["start_time"]
final_score = calculate_score(nbmIngredient, difficulty, time_taken)
session["score"] = final_score
return redirect("/resultats")
cocktail_info = {
'strDrink': nom,
'strCategory': "Cocktail",
'strDrinkThumb': img
}
info_affiche = mask_info_by_difficulty(cocktail_info, difficulty)
return render_template(
"play.html",
cocktail=info_affiche,
ingredients=ingredients,
nbmIngredient=nbmIngredient,
difficulty=difficulty,
message=message
)
@app.route("/resultats")
def resultats_page():
score = session.get('score', 0)
return render_template('score.html', score=score)
@app.route('/save_score', methods=['POST'])
def save_score():
l1 = request.form.get('l1', 'A')
l2 = request.form.get('l2', 'A')
l3 = request.form.get('l3', 'A')
pseudo = f"{l1}{l2}{l3}"
score = session.get('score', 0)
cocktail_data = session.get("cocktail", {})
cocktail_name = cocktail_data.get("nom", "Cocktail Mystère")
if pseudo:
conn = sqlite3.connect('Score.db')
cursor = conn.cursor()
cursor.execute('INSERT INTO user (nom_j, cocktail, score) VALUES (?, ?, ?)',
(pseudo, cocktail_name, score))
conn.commit()
conn.close()
session.pop("cocktail", None)
session.pop("score", None)
return redirect(url_for('classement'))
@app.route('/classement')
def classement():
conn = sqlite3.connect('Score.db')
cursor = conn.cursor()
cursor.execute('SELECT nom_j, score FROM user ORDER BY score DESC LIMIT 10')
top_scores = cursor.fetchall()
conn.close()
return render_template('classement.html', scores=top_scores)
# ------------------------------------------------------------------------------------------------
# -------------------------------- Fonctions Utilitaires -----------------------------------------
# ------------------------------------------------------------------------------------------------
def getRandomCocktailFromAPI():
try:
r = requests.get("https://www.thecocktaildb.com/api/json/v1/1/random.php")
data = r.json()
if not data['drinks']: return None
cocktail = data['drinks'][0]
nom = cocktail['strDrink']
img = cocktail['strDrinkThumb']
ingredient = []
for i in range(1,16):
ing = cocktail.get(f'strIngredient{i}')
if ing:
ingredient.append(ing)
return nom, img, ingredient, len(ingredient)
except:
# Fallback en cas d'erreur API
return "Mojito", "", ["Rhum", "Menthe", "Sucre", "Citron vert", "Eau gazeuse"], 5
def getValideIngredient(user_input, ingredients):
user_input = user_input.lower()
for i, ingredient in enumerate(ingredients):
# On compare avec une tolérance de 85%
ratio = SequenceMatcher(None, ingredient.lower(), user_input).ratio() * 100
if ratio > 85:
ingredients.pop(i) # On retire l'ingrédient trouvé
return ingredients
return ingredients
def mask_info_by_difficulty(cocktail, difficulty):
info = {
'nom': cocktail['strDrink'],
'category': 'Cocktail Mystère',
'image': cocktail['strDrinkThumb']
}
if difficulty == "facile":
pass # On laisse tout
elif difficulty == "moyen":
info['nom'] = '???' # On cache le nom
elif difficulty == "difficile":
info['image'] = None # On cache l'image
return info
if __name__ == "__main__":
app.run(debug=True)
def calculate_score(nb_ingredients, difficulty, time_taken):
"""Calcule le score basé sur la difficulté, le nombre d'ingrédients, et le temps."""
base_score = 100
ingredient_bonus = nb_ingredients * 50
multiplier = 1
if difficulty == "moyen":
multiplier = 2
elif difficulty == "difficile":
multiplier = 3
time_penalty = max(0, 50 - int(time_taken / 2))
score = (base_score + ingredient_bonus + time_penalty) * multiplier
return max(1, int(score))