This repository was archived by the owner on Dec 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbagels.py
More file actions
91 lines (64 loc) · 2.23 KB
/
Copy pathbagels.py
File metadata and controls
91 lines (64 loc) · 2.23 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
#! python3
"""Bagels
A deductive logic game where you must guess a number based on clues.
View this code at https://nostarch.com/big-book-small-python-projects
A version of this game is featured in the book "Invent Your Own
Computer Games with Python" https://nostarch.com/inventwithpython
Tags: short, game, puzzle
"""
import random
import sys
NUM_DIGITS = 3
MAX_GUESSES = 10
def getSecretNum():
return "".join(str(random.randint(0, 9)) for _ in range(NUM_DIGITS))
def getClues(guess: str, secretNum: str):
if guess == secretNum:
return "You got it!"
clues = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
clues.append("Fermi")
elif guess[i] in secretNum:
clues.append("Pico")
if len(clues) == 0:
return "Bagels"
clues.sort()
return " ".join(clues)
def main():
print(
f"""Bagels, a deductive logic game.
I am thinking of a {NUM_DIGITS}-digit number with no repeated digits.
Try to guess what it is. Here are some clues:
When I say: That means:
Pico One digit is correct but in the wrong position.
Fermi One digit is correct and in the right position.
Bagels No digit is correct.
For example, if the secret number was 248 and your guess was 843, the clues would be Fermi Pico.
"""
)
while True:
secretNum = getSecretNum()
print("I have thought up a number.")
print(f" You have {MAX_GUESSES} guesses to get it.")
for numGuesses in range(1, MAX_GUESSES + 1):
guess = ""
while len(guess) != NUM_DIGITS or not guess.isdecimal():
print(f"Guess #{numGuesses}: ")
guess = input("> ")
clues = getClues(guess, secretNum)
print(clues)
if guess == secretNum:
break
if numGuesses >= MAX_GUESSES:
print("You ran out of guesses.")
print(f"The answer was {secretNum}.")
print("Do you want to play again? (yes or no)")
if not input("> ").lower().startswith("y"):
break
print("Thanks for playing!")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)