Skip to content

Commit 7b9074f

Browse files
committed
create calculator game
1 parent 99b20b8 commit 7b9074f

File tree

3 files changed

+63
-3
lines changed

3 files changed

+63
-3
lines changed

brain_games/games/brain_calc.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import random
2+
3+
4+
# Brain Calculator Game
5+
def generate_expression():
6+
# Generate a random arithmetic expression.
7+
operators = ['+', '-', '*']
8+
num1 = random.randint(1, 25)
9+
num2 = random.randint(1, 25)
10+
operator = random.choice(operators)
11+
expression = f"{num1} {operator} {num2}"
12+
return expression
13+
14+
15+
def get_user_name():
16+
# Get the user's name.
17+
return input("May I have your name? ")
18+
19+
20+
def play_brain_calc():
21+
score = 0
22+
round = 3
23+
# Play the Brain Calculator game.
24+
print("Welcome to the Brain Games!")
25+
name = get_user_name()
26+
print(f"Hello, {name}!")
27+
print("What is the result of the expression?")
28+
29+
# Game loop
30+
while score < round:
31+
# Generate a random expression
32+
expression = generate_expression()
33+
print(f"Question: {expression}")
34+
# Calculate the correct answer
35+
correct_answer = eval(expression)
36+
# Check user input
37+
while True:
38+
user_answer_str = input("Your answer: ").strip()
39+
if user_answer_str.lstrip('-').isdigit():
40+
user_answer_num = int(user_answer_str)
41+
user_answer = user_answer_num
42+
break
43+
else:
44+
print("Please enter a valid integer.")
45+
# Check if the answer is correct
46+
if user_answer == correct_answer:
47+
score += 1
48+
print("Correct!")
49+
else:
50+
score = 0
51+
print(f"'{user_answer}' is wrong answer ;(. Correct answer was '{correct_answer}'.")
52+
print(f"Let's try again, {name}")
53+
print(f"Congratulations, {name}!")

brain_games/games/brain_even.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,9 @@ def play_brain_even():
2525
while score < rounds:
2626
# Generate a random number
2727
number = random.randint(1, 100)
28-
print(f"Question: {number}")
29-
28+
print(f"Question: {number}")
3029
# Get user input
3130
user_answer = input("Your answer: ").strip().lower()
32-
3331
# Check if the answer is correct
3432
if (is_even(number) and user_answer == "yes") or (not is_even(number) and user_answer == "no"):
3533
score += 1

brain_games/scripts/brain_calc.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from brain_games.games.brain_calc import play_brain_calc
2+
3+
4+
def main():
5+
play_brain_calc()
6+
7+
8+
if __name__ == '__main__':
9+
main()

0 commit comments

Comments
 (0)