Created
June 4, 2014 00:08
-
-
Save tomlins/4b18655ccaf3f0baf672 to your computer and use it in GitHub Desktop.
Guess The Number - My first proper Python program as I learn the language. If any Python experts can offer a refactored version, that would be great.
This file contains hidden or 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
#!/usr/bin/python | |
import random | |
print ("A Simple find the number game.") | |
score_table = {} | |
def get_high_scores(): | |
high_score = 0 | |
high_score_holder = None | |
f = open('highscores.txt', 'r') | |
for line in f: | |
score_entry = line.split() | |
if score_entry[1] > high_score: | |
high_score_holder = score_entry[0] | |
high_score = score_entry[1] | |
score_table.update({score_entry[0]:score_entry[1]}) | |
f.close() | |
print("High scores table read.") | |
return (high_score_holder,high_score) | |
def update_high_score_table(name, tries): | |
score_table.update({name:str(tries)}) | |
f = open('highscores.txt', 'w') | |
for name, score in score_table.iteritems(): | |
f.write(name + ' ' + score + "\n") | |
print("Score table file written.") | |
high_score = get_high_scores() | |
if score_table: | |
print("%s is the current champion with just %s tries" %(high_score[0],high_score[1])) | |
tries = 9999 | |
name = raw_input("Please enter your name >") | |
if name in score_table: | |
tries = int(score_table.get(name)) | |
print("Welcome back, %s. Your best is %s tries." %(name, tries)) | |
secret_number = random.randint(1, 100) | |
print ("I have thought of a number between 1 and 100. Can you guess it?") | |
guessed = False | |
number_of_trys = 1 | |
while guessed is False: | |
my_guess = int(raw_input("Enter your guess >")) | |
if my_guess == secret_number: | |
print ("Correct! You got it in %i tries!" %number_of_trys) | |
guessed = True | |
else: | |
higher_lower = "lower" | |
if my_guess < secret_number: | |
higher_lower = "higher" | |
print("Sorry, incorrect. Try %s." % higher_lower) | |
number_of_trys += 1 | |
update_score_table = False | |
if high_score[1] == 0 or number_of_trys < int(high_score[1]): | |
print("Congratulations %s! You are the new champion!" %(name)) | |
update_score_table = True | |
elif number_of_trys < tries: | |
print("Congratulations %s! You have a new personal best of %s tries!" %(name, number_of_trys)) | |
update_score_table = True | |
if update_score_table: | |
update_high_score_table(name, number_of_trys) | |
print("Goodbye.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment