keerthuAi commited on
Commit
47de747
·
verified ·
1 Parent(s): cb21542

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -253
app.py CHANGED
@@ -6,269 +6,89 @@ import random
6
  # ------------------------
7
 
8
  quiz_questions = [
9
- {
10
- "code": 'print("Hello" + "World")',
11
- "options": ["HelloWorld", "Hello World", "Hello+World"],
12
- "answer": "HelloWorld",
13
- "hint": "What happens when you add two strings?"
14
- },
15
- {
16
- "code": 'print(2 * 3)',
17
- "options": ["6", "23", "5"],
18
- "answer": "6",
19
- "hint": "Multiplication or joining?"
20
- },
21
- {
22
- "code": 'x = 5\nprint(x + 2)',
23
- "options": ["7", "52", "2"],
24
- "answer": "7",
25
- "hint": "What is 5 + 2?"
26
- },
27
- {
28
- "code": 'print(10 / 2)',
29
- "options": ["5", "2", "20"],
30
- "answer": "5",
31
- "hint": "What is 10 divided by 2?"
32
- },
33
- {
34
- "code": 'x = "Python"\nprint(x[0])',
35
- "options": ["P", "y", "t"],
36
- "answer": "P",
37
- "hint": "What is the first letter of 'Python'?"
38
- },
39
- {
40
- "code": 'x = [1, 2, 3]\nprint(x[1])',
41
- "options": ["2", "3", "1"],
42
- "answer": "2",
43
- "hint": "Which number is at the second position in the list?"
44
- },
45
- {
46
- "code": 'x = "Code"\nprint(x[::-1])',
47
- "options": ["edoC", "Code", "CdeO"],
48
- "answer": "edoC",
49
- "hint": "What does slicing the string backwards give?"
50
- }
51
  ]
52
 
53
- quiz_score = 0
54
- quiz_index = 0
55
- quiz_history = []
56
-
57
- def get_quiz_question():
58
- return quiz_questions[quiz_index]
59
-
60
- def show_quiz_question():
61
- q = get_quiz_question()
62
- return q["code"], gr.update(choices=q["options"]), "", f"⭐ Score: {quiz_score}"
63
-
64
- def check_quiz_answer(choice):
65
- global quiz_score
66
- correct = get_quiz_question()["answer"]
67
- result = ""
68
- if choice == correct:
69
- result = "✅ Correct! Great job!"
70
- quiz_score += 1
71
- else:
72
- result = f"❌ Oops! The correct answer was: {correct}"
73
- return result, f"⭐ Score: {quiz_score}"
74
-
75
- def quiz_skip():
76
- next_quiz()
77
- return show_quiz_question()
78
-
79
- def quiz_hint():
80
- return f"💡 Hint: {get_quiz_question()['hint']}"
81
-
82
- def next_quiz():
83
- global quiz_index
84
- quiz_history.append(quiz_index)
85
- quiz_index = (quiz_index + 1) % len(quiz_questions)
86
-
87
- def prev_quiz():
88
- global quiz_index
89
- if quiz_history:
90
- quiz_index = quiz_history.pop()
91
- return show_quiz_question()
92
-
93
  # ------------------------
94
- # 🔤 2. WORD SCRAMBLE GAME
95
  # ------------------------
96
 
97
- scramble_words = [
98
- ("python", "A popular programming language"),
99
- ("loop", "Used to repeat code"),
100
- ("print", "Outputs something on screen"),
101
- ("variable", "Stores data values"),
102
- ("function", "Encapsulates code into reusable blocks"),
103
- ("list", "A collection of items"),
104
- ("string", "A sequence of characters")
105
  ]
106
 
107
- def scramble_word(word):
108
- return ''.join(random.sample(word, len(word)))
109
-
110
- current_scramble = random.choice(scramble_words)
111
-
112
- def show_scramble():
113
- global current_scramble
114
- current_scramble = random.choice(scramble_words)
115
- return scramble_word(current_scramble[0]), ""
116
-
117
- def check_scramble_answer(ans):
118
- correct = current_scramble[0]
119
- if ans.lower() == correct:
120
- return "✅ Awesome! That's correct!"
121
- else:
122
- return f"❌ Nope! The right word was '{correct}'."
123
-
124
  # ------------------------
125
- # 🎲 3. CODE DICE
126
  # ------------------------
127
 
128
- dice_challenges = [
129
- "💡 Create a variable and assign it your name",
130
- "💡 Write code to add 2 + 3 and print it",
131
- "💡 Use a loop to print numbers from 1 to 5",
132
- "💡 Print your favorite color 3 times",
133
- "💡 Write a program to check if a number is even or odd",
134
- "💡 Create a list and add 3 items to it",
135
- "💡 Write a function that takes two numbers and returns their sum"
136
  ]
137
 
138
- def roll_dice():
139
- return random.choice(dice_challenges)
140
-
141
- # ------------------------
142
- # 🧩 4. PUZZLE BLOCKS (Ordering)
143
- # ------------------------
144
-
145
- puzzle_code = [
146
- "x = 5",
147
- "y = 3",
148
- "z = x + y",
149
- "print(z)"
150
- ]
151
-
152
- correct_order = "\n".join(puzzle_code)
153
-
154
- def check_code_order(user_code):
155
- if user_code.strip() == correct_order:
156
- return "✅ Perfect order! You built it right!"
157
- else:
158
- return "❌ Hmm... Try again! The order seems off."
159
-
160
- # ------------------------
161
- # 📚 5. CODE FAIRY TALE
162
- # ------------------------
163
-
164
- fairy_code = 'print("Cinderella" * 2)'
165
- fairy_answer = "CinderellaCinderella"
166
-
167
- def check_fairy_ans(ans):
168
- if ans.strip() == fairy_answer:
169
- return "✨ Correct! Cinderella doubled!"
170
- else:
171
- return "❌ Not quite, try again!"
172
-
173
  # ------------------------
174
- # 💻 6. SIMPLE CALCULATOR
175
- # ------------------------
176
-
177
- def add(x, y):
178
- return x + y
179
-
180
- def subtract(x, y):
181
- return x - y
182
-
183
- def multiply(x, y):
184
- return x * y
185
-
186
- def divide(x, y):
187
- if y != 0:
188
- return x / y
189
- return "❌ Cannot divide by zero!"
190
-
191
- # ------------------------
192
- # 🎨 7. GUESS THE NUMBER
193
- # ------------------------
194
-
195
- target_number = random.randint(1, 100)
196
-
197
- def guess_number(guess):
198
- global target_number
199
- if guess < target_number:
200
- return "⬆️ Try a higher number!"
201
- elif guess > target_number:
202
- return "⬇️ Try a lower number!"
203
- else:
204
- target_number = random.randint(1, 100) # Reset after correct guess
205
- return "🎉 Correct! Well done!"
206
-
207
- # ------------------------
208
- # 🎨 UI
209
- # ------------------------
210
-
211
- with gr.Blocks(theme=gr.themes.Base(primary_hue="purple", secondary_hue="pink")) as app:
212
- gr.Markdown("## 🧒✨ Welcome to Python FunLand! 🎮 Learn Python by Playing")
213
-
214
- with gr.Tabs():
215
- with gr.TabItem("🎯 Guess the Output"):
216
- with gr.Row():
217
- score_box = gr.Textbox(label="📊 Score", value="⭐ Score: 0", interactive=False)
218
- hint_box = gr.Textbox(label="💡 Hint", interactive=False)
219
- code_display = gr.Textbox(label="🧠 What will this Python code print?", interactive=False)
220
- options = gr.Radio(choices=[], label="Your Answer")
221
- result = gr.Textbox(label="🎯 Result", interactive=False)
222
-
223
- with gr.Row():
224
- gr.Button("✅ Check Answer").click(fn=check_quiz_answer, inputs=options, outputs=[result, score_box])
225
- gr.Button("💡 Get Hint").click(fn=quiz_hint, outputs=hint_box)
226
- gr.Button("⏭️ Skip").click(fn=quiz_skip, outputs=[code_display, options, result, score_box])
227
- gr.Button("⏪ Back").click(fn=prev_quiz, outputs=[code_display, options, result, score_box])
228
-
229
- app.load(show_quiz_question, outputs=[code_display, options, result, score_box])
230
-
231
- with gr.TabItem("🔤 Word Scramble"):
232
- scramble_display = gr.Textbox(label="Unscramble This Word", interactive=False)
233
- word_input = gr.Textbox(label="Your Answer")
234
- scramble_result = gr.Textbox(label="Result", interactive=False)
235
- gr.Button("🔄 New Word").click(fn=show_scramble, outputs=[scramble_display, scramble_result])
236
- gr.Button("✅ Submit").click(fn=check_scramble_answer, inputs=word_input, outputs=scramble_result)
237
-
238
- with gr.TabItem("🎲 Code Dice"):
239
- gr.Markdown("🎲 Click to roll a coding challenge!")
240
- dice_output = gr.Textbox(label="Challenge", interactive=False)
241
- gr.Button("🎲 Roll Dice").click(fn=roll_dice, outputs=dice_output)
242
-
243
- with gr.TabItem("🧩 Puzzle Blocks"):
244
- gr.Markdown("🧩 Arrange the code blocks in the correct order and paste below:")
245
- user_order = gr.Textbox(label="Paste Your Ordered Code", lines=5)
246
- puzzle_result = gr.Textbox(label="Result", interactive=False)
247
- gr.Button("✅ Submit").click(fn=check_code_order, inputs=user_order, outputs=puzzle_result)
248
-
249
- with gr.TabItem("📚 Code Fairy Tales"):
250
- gr.Markdown("🧚 Imagine what this code prints:")
251
- gr.Textbox(label="Code", value=fairy_code, interactive=False)
252
- fairy_input = gr.Textbox(label="Your Answer")
253
- fairy_result = gr.Textbox(label="Result", interactive=False)
254
- gr.Button("✅ Submit").click(fn=check_fairy_ans, inputs=fairy_input, outputs=fairy_result)
255
-
256
- with gr.TabItem("💻 Simple Calculator"):
257
- gr.Markdown("🧮 Let's do some math!")
258
- num1 = gr.Number(label="Enter first number")
259
- num2 = gr.Number(label="Enter second number")
260
- operation = gr.Radio(choices=["Add", "Subtract", "Multiply", "Divide"], label="Choose Operation")
261
- calc_result = gr.Textbox(label="Result", interactive=False)
262
- gr.Button("✅ Calculate").click(fn=lambda n1, n2, op: {
263
- "Add": add(n1, n2),
264
- "Subtract": subtract(n1, n2),
265
- "Multiply": multiply(n1, n2),
266
- "Divide": divide(n1, n2)
267
- }[operation], inputs=[num1, num2, operation], outputs=calc_result)
268
-
269
- with gr.TabItem("🎯 Guess the Number"):
270
- gr.Markdown("🎮 Guess the number between 1 and 100!")
271
- number_guess = gr.Number(label="Your Guess", interactive=True)
272
- guess_result = gr.Textbox(label="Result", interactive=False)
273
- gr.Button("✅ Check Guess").click
274
-
 
6
  # ------------------------
7
 
8
  quiz_questions = [
9
+ {"code": 'print("Hello" + "World")', "options": ["HelloWorld", "Hello World", "Hello+World"], "answer": "HelloWorld", "hint": "What happens when you add two strings?"},
10
+ {"code": 'print(2 * 3)', "options": ["6", "23", "5"], "answer": "6", "hint": "Multiplication or joining?"},
11
+ {"code": 'x = 5\nprint(x + 2)', "options": ["7", "10", "5"], "answer": "7", "hint": "Adding a number to a variable."},
12
+ {"code": 'print(3 + 5 * 2)', "options": ["13", "16", "8"], "answer": "13", "hint": "Order of operations."},
13
+ {"code": 'print("Python"[0])', "options": ["P", "Y", "p"], "answer": "P", "hint": "What does the index 0 in a string return?"},
14
+ {"code": 'x = [1, 2, 3]\nprint(x[1])', "options": ["2", "3", "1"], "answer": "2", "hint": "Indexing a list."},
15
+ {"code": 'print("5" + "5")', "options": ["10", "55", "50"], "answer": "55", "hint": "What happens when you add strings?"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  ]
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  # ------------------------
19
+ # 🎮 2. MATH CHALLENGE
20
  # ------------------------
21
 
22
+ math_questions = [
23
+ {"question": "What is 5 + 3?", "options": ["8", "7", "9"], "answer": "8", "hint": "Simple addition."},
24
+ {"question": "What is 6 * 4?", "options": ["24", "26", "23"], "answer": "24", "hint": "Multiplication."},
25
+ {"question": "What is 9 - 2?", "options": ["7", "6", "5"], "answer": "7", "hint": "Simple subtraction."},
26
+ {"question": "What is 12 / 3?", "options": ["3", "4", "5"], "answer": "4", "hint": "Division."},
27
+ {"question": "What is 15 % 4?", "options": ["3", "4", "5"], "answer": "3", "hint": "Modulo operation."},
28
+ {"question": "What is 8 * 7?", "options": ["56", "54", "58"], "answer": "56", "hint": "Multiplication."},
29
+ {"question": "What is 5 + 9?", "options": ["14", "13", "12"], "answer": "14", "hint": "Addition."}
30
  ]
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  # ------------------------
33
+ # 🎮 3. PYTHON BASICS QUIZ
34
  # ------------------------
35
 
36
+ python_basics_questions = [
37
+ {"question": "What does 'int' represent in Python?", "options": ["Integer", "Index", "Iterator"], "answer": "Integer", "hint": "Type of number."},
38
+ {"question": "What does 'def' keyword do?", "options": ["Defines a function", "Defines a variable", "Defines a class"], "answer": "Defines a function", "hint": "Function definition."},
39
+ {"question": "What is a list in Python?", "options": ["A collection of items", "A single item", "An integer"], "answer": "A collection of items", "hint": "Data structure."},
40
+ {"question": "What does 'print()' do?", "options": ["Prints a string", "Prints an integer", "Prints a value"], "answer": "Prints a value", "hint": "Output function."},
41
+ {"question": "What is the symbol for power in Python?", "options": ["**", "*", "^"], "answer": "**", "hint": "Exponentiation."},
42
+ {"question": "What is the use of 'input()'?", "options": ["To take user input", "To print a value", "To define a function"], "answer": "To take user input", "hint": "User interaction."},
43
+ {"question": "What is a tuple?", "options": ["Immutable list", "Mutable list", "String"], "answer": "Immutable list", "hint": "Cannot be changed after creation."}
44
  ]
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  # ------------------------
47
+ # GAME LOGIC
48
+ # ------------------------
49
+
50
+ # For simplicity, let's use a general function to handle quiz games
51
+ def quiz_game(questions, game_type):
52
+ score = 0
53
+ current_question = random.choice(questions)
54
+ question_text = current_question['question'] if 'question' in current_question else current_question['code']
55
+ options = current_question['options']
56
+ answer = current_question['answer']
57
+ hint = current_question['hint']
58
+
59
+ def check_answer(user_answer):
60
+ nonlocal score
61
+ if user_answer == answer:
62
+ score += 1
63
+ return score, f"Hint: {hint} - Next Question"
64
+
65
+ return gr.Interface(
66
+ fn=check_answer,
67
+ inputs=[gr.Dropdown(choices=options, label=f"{game_type}: {question_text}")],
68
+ outputs=[gr.Textbox(label="Your Score"), gr.Textbox(label="Hint")],
69
+ live=True
70
+ )
71
+
72
+ # ------------------------
73
+ # GRADIO APP
74
+ # ------------------------
75
+
76
+ # Create a Gradio interface to show multiple games
77
+ def launch_game():
78
+ game_choices = ["Guess the Output Quiz", "Math Challenge", "Python Basics Quiz"]
79
+ game_type = gr.Dropdown(choices=game_choices, label="Select a Game")
80
+ game = gr.Button("Start Game")
81
+
82
+ def start_game(choice):
83
+ if choice == "Guess the Output Quiz":
84
+ return quiz_game(quiz_questions, choice)
85
+ elif choice == "Math Challenge":
86
+ return quiz_game(math_questions, choice)
87
+ elif choice == "Python Basics Quiz":
88
+ return quiz_game(python_basics_questions, choice)
89
+
90
+ game.click(start_game, inputs=[game_type], outputs=["game_window"])
91
+ return gr.Interface(fn=start_game, inputs=[game_type, game], outputs=["game_window"], live=True)
92
+
93
+ # Launch the Gradio interface
94
+ launch_game().launch()