Guessing Game with functions, classes, methods, etc
#Code should always be in a method or class
#Always start variable names with lowercase, classes could be capital
#input.upper() allows the user to use lower or upper case for each option
import random
from operator import itemgetter
def isint(x):
try:
int(x)
return True
except:
return False
print "Invalid guess. "
def getGuessValidator():
while True:
strInput = raw_input("Please enter your guess, between 1 and 42: ")
if isint(strInput) == True:
strInput = int(strInput)
if strInput >42 or strInput <1:
print "Invalid guess. "
else:
return strInput
else:
print "Invalid guess. "
class GuessingGame:
def __init__(self):
self.menu = '''\nMenu:\n(V)iew High Scores\n(P)lay Game\n(Q)uit Game'''
def getNameFromUser(self):
self.yourName = raw_input('What is your name? ')
def displayMenu(self):
while True:
print self.menu
input = raw_input("")
if input.upper() == "V":
fileHandle = open ( 'scores.txt', 'r' )
str1 = fileHandle.read().strip()
fileHandle.close()
list1 = str1.split("\n")
list2 = []
for str2 in list1:
list3 = str2.split(",")
list3[1]= int(list3[1])
list2.append(list3)
list2 = sorted(list2, key=itemgetter(1)) #this will sort the scores.txt file into 2 lists and then merge them back into 1 list that is sorted by the score.
print "High Scores: "
for str2 in list2:
print "%-20s %5s" %(str2[0], str2[1])
elif input.upper() == "P":
self.gameMode() #using self. to call method from inside the class
elif input.upper() == "Q":
print "Thank you for playing. "
return
else:
print "Invalid menu choice. "
def gameMode(self):
number = random.randint(1, 42)
guess = -1
self.guessesTaken = 0
while guess != number:
guess = getGuessValidator()
if guess < number:
print 'My number is higher.'
elif guess > number:
print 'My number is lower.'
self.guessesTaken += 1
if guess == number:
print 'Good job, ' + self.yourName + '! You guessed my number in',self.guessesTaken,'guesses!'
self.saveScore()
def saveScore(self):
print "\nWould you like to save your score? (Y)es or (N)o:"
inp = raw_input().upper();
if inp == "Y":
saveStr = self.yourName + ', ' + str(self.guessesTaken) + "\n"
fileHandle = open ( 'scores.txt', 'a' ) #the use of 'a' will append the score to the scores.txt instead of overwriting the original data
fileHandle.write(saveStr)
fileHandle.close()
print "Saving high scores file... "
return
def main():
game = GuessingGame() #Constructing the game
game.getNameFromUser()
game.displayMenu() #runs the menu, which then has all the options
if __name__ == "__main__":
main()
The same code minus defined functions, classes, etc
import random
from operator import itemgetter
isint(x)
try:
int(x)
return True
except:
return False
print "Invalid guess. "
getGuessValidator():
while True:
strInput = raw_input("Please enter your guess, between 1 and 42: ")
if isint(strInput) == True:
strInput = int(strInput)
if strInput >42 or strInput <1:
print "Invalid guess. "
else:
return strInput
else:
print "Invalid guess. "
__init__(self):
self.menu = '''\nMenu:\n(V)iew High Scores\n(P)lay Game\n(Q)uit Game'''
getNameFromUser(self):
self.yourName = raw_input('What is your name? ')
displayMenu(self):
while True:
print self.menu
input = raw_input("")
if input.upper() == "V":
fileHandle = open ( 'scores.txt', 'r' )
str1 = fileHandle.read().strip()
fileHandle.close()
list1 = str1.split("\n")
list2 = []
for str2 in list1:
list3 = str2.split(",")
list3[1]= int(list3[1])
list2.append(list3)
list2 = sorted(list2, key=itemgetter(1)) #this will sort the scores.txt file into 2 lists and then merge them back into 1 list that is sorted by the score.
print "High Scores: "
for str2 in list2:
print "%-20s %5s" %(str2[0], str2[1])
elif input.upper() == "P":
self.gameMode() #using self. to call method from inside the class
elif input.upper() == "Q":
print "Thank you for playing. "
return
else:
print "Invalid menu choice. "
gameMode(self):
number = random.randint(1, 42)
guess = -1
self.guessesTaken = 0
while guess != number:
guess = getGuessValidator()
if guess < number:
print 'My number is higher.'
elif guess > number:
print 'My number is lower.'
self.guessesTaken += 1
if guess == number:
print 'Good job, ' + self.yourName + '! You guessed my number in',self.guessesTaken,'guesses!'
self.saveScore()
saveScore(self):
print "\nWould you like to save your score? (Y)es or (N)o:"
inp = raw_input().upper();
if inp == "Y":
saveStr = self.yourName + ', ' + str(self.guessesTaken) + "\n"
fileHandle = open ( 'scores.txt', 'a' ) #the use of 'a' will append the score to the scores.txt instead of overwriting the original data
fileHandle.write(saveStr)
fileHandle.close()
print "Saving high scores file... "
return
main():
game = GuessingGame() #Constructing the game
game.getNameFromUser()
game.displayMenu() #runs the menu, which then has all the options
if __name__ == "__main__":
main()
The problem is that when it is run, I get syntax and indentation errors from Python IDLE. Also the second code may look terrible (and I believe it is), but that is how python decided to indent it. The top code is fine and doesn't need work, the second code is where I am stumped. I need it to work without and functions, classes or methods like the first. Unless methods have to be used.