Last active
December 20, 2015 12:39
-
-
Save jeremyosborne/6133016 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 1) Ask the user their name. | |
# 2) Generate a random number between 1 and 20. | |
# 3) Give the user 5 guesses to guess the number. | |
# 4) If the user is wrong, tell them "high" or "low" | |
# 5) If they user is right, tell them they won and exit. | |
# 6) If they don't get the answer right in 5 tries, tell | |
# them they lost and exit. | |
# | |
# EXTRA CREDIT | |
# 1) Save the win loss record of the player. | |
# Hint: save it in a flat text file. | |
# Hint: check out the stdlib "shelve" | |
# Hint: check out the "json" stdlib | |
# 2) Display the win loss record at the start of a game. | |
# https://gist.github.com/jeremyosborne/6133016 | |
from random import randint | |
import shelve | |
stats = shelve.open("guess_stats.shelf") | |
name = raw_input("What is your name?") | |
name = str(name) | |
if name in stats: | |
print "Welcome back", name | |
user_stats = stats[name] | |
else: | |
print "Welcome to the game", name | |
user_stats = {"wins": 0, "losses": 0} | |
print "You have %s wins and %s losses" % (user_stats["wins"], | |
user_stats["losses"]) | |
random_number = randint(1, 20) | |
for i in range(5): | |
guess = raw_input("What is your guess (between 1 and 20)?") | |
# guess is a string at first.... | |
try: | |
guess = int(guess) | |
if guess > 20 or guess < 0: | |
print "Please give me a number between 1 and 20." | |
elif guess > random_number: | |
print "Too high." | |
elif guess < random_number: | |
print "Too low." | |
else: | |
#print "You win!" | |
break | |
except ValueError: | |
print "Please type a number." | |
# Problem with above code... how can I tell if the player lost? | |
# a solution... check win conditions after the for loop. | |
if guess == random_number: | |
print "You win!" | |
user_stats["wins"] += 1 | |
else: | |
print "So sorry, you lost." | |
user_stats["losses"] += 1 | |
stats[name] = user_stats | |
stats.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment