Skip to content

Instantly share code, notes, and snippets.

@DangerOnTheRanger
Created December 9, 2017 17:03
Show Gist options
  • Save DangerOnTheRanger/656a99274c677aac5c4ca12855670278 to your computer and use it in GitHub Desktop.
Save DangerOnTheRanger/656a99274c677aac5c4ca12855670278 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import getpass
import random
MAX_GUESSES = 7
SCORE_FILENAME = "gamescores"
def genrandom(min_num, max_num):
# delegate to the Python stdlib
return random.randint(min_num, max_num)
def get_guess():
while True:
try:
num = int(input("Enter a number: "))
except ValueError:
print("Not a number, please try again.")
else:
return num
def record_score(score):
score_file = open(SCORE_FILENAME, "a")
score_file.write("%s %s\n" % (getpass.getuser(), score))
score_file.close()
def main():
rand = genrandom(-100, 100)
guesses = 0
print("Allowed number of guesses:", MAX_GUESSES)
while True:
num = get_guess()
guesses += 1
if num == rand:
print("Correct!")
break
elif num > rand:
print("Too high!")
else:
print("Too low!")
if guesses == MAX_GUESSES:
print("Game over!")
print("The number was:", rand)
break
print("Your score:", guesses)
record_score(guesses)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment