/
guess-the-number.py
117 lines (91 loc) · 2.45 KB
/
guess-the-number.py
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
# Guess the number game
from art import logo, yay, oh_no
import random
from replit import clear
def introduction():
"""
Function that prints the intro message at the beginning of the game and returns random number [1, 100]
"""
clear()
print(logo)
print("Welcome to the Guessing Number Game!")
print("I'm thinking of a number between 1 and 100.")
return random.randint(1, 100)
def difficulty():
"""
Function that selects difficulty level and returns initial tries
"""
difficulties = ["easy", "hard"]
player_level = 0
# Handle any other input than easy or hard
while player_level not in difficulties:
player_level = input("Choose a difficulty. Type 'easy' or 'hard': ").lower()
if player_level == "easy":
tries = 10
else:
tries = 5
return tries
def guess_number():
'''
Asks user to guess an integer between 1 and 100
'''
guess_ok = False
while not guess_ok:
try:
guess = int(input("Make a guess: "))
if guess > 0 and guess <= 100:
guess_ok = True
else:
print("Your guess is not a number between 1 and 100.")
except ValueError:
print("Your guess is not a number between 1 and 100.")
return guess
def compare(guess, number):
'''
Compare guessed number with the random number.
'''
if guess < number:
return 1
elif guess > number:
return 2
else:
return 3
def play_again():
print("\n")
play_options = ["y", "n"]
play_select = 0
while play_select not in play_options:
play_select = input("Play again? [y/n] ").lower()
if play_select == "y":
return main()
def main():
## Introduction message
## Generate the number
number = introduction()
## Choose difficulty
tries_left = difficulty()
while tries_left > 0:
print("\n")
## Tell user how many attempts he has left
print(f"You have {tries_left} attempts remaining to guess the number.")
## Ask user to make a Guess
guess = guess_number()
## Tell user if guess is too low or too high
if compare(guess, number) == 1:
print("Too low.")
print("Guess again.")
elif compare(guess, number) == 2:
print("Too high.")
print("Guess again.")
else:
print(yay)
print(f"You got it! The answer is {guess}")
break
tries_left -= 1
## If number of guesses ran out, game over
if tries_left == 0:
print(oh_no)
print("You've run out of guesses, you lose.")
play_again()
if __name__ == main():
main()