Search code examples
pythonpython-3.xmemory-efficient

Reduce line count or make this code more efficient


In my evergrowing quest for knowledge I would like to know if there is any way I can reduce the line count or make the code more efficient. Its for a game I have made and I have challenged myself to make it as short as I can, (in the original it was about twice as long as this :D)

import random
gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
def is_valid(guess):
    try:
        guess=int(guess)
        return True,guess
    except:
        print("Try again, not a number")
        repeat=1
def GameLevel(Range,gameLives,level,hints):
    lives,hints,targetnumber,repeat=gameLives,hints,random.randint(1,1),1
    print("LEVEL {}\nThinking...".format(level))
    if level>1:
        print("You now have {} lives remaining".format(gameLives))
    if level==10:
        print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
    print("This number is between 1 and "+str(Range))
    while repeat==1:
        guess=input("What is your guess? ")
        guess,repeat,targetnumber=guess.lower(),0,str(targetnumber)
        if guess=="hint":
            if level>=3:
                if hints!=1:
                    targetnumber=int(targetnumber)
                    print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
                    repeat,hints=1,hints-1
                else:
                    print("Sorry you have ran out of hints :(")
                    repeat=1
            else:
                print("Hints are not available until level 3")
                repeat=1
        elif guess==targetnumber:
            print("Well done, You have guessed my number!")
            return lives,hints
        elif guess!=targetnumber:
            if is_valid(guess)==True:
                print("Sorry that is not my number, you have lost a life. :(")
                targetnumber,lives,repeat=int(targetnumber),lives-1,1
                if lives<=0:
                    print("You have lost all your lives, so this means I win\nThe program will now end")
                    input("")
                    exit()
                if guess<targetnumber:
                    print("The target number is higher")
                else:
                    print("The target number is lower")
            else:
                repeat=1
print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)))
a,b=0,0
for level in levels:
    Range=levelRange[a]
    gameLives,hints=GameLevel(Range,gameLives,level,hints)
    if gameLives>0 and wonGame!=10:
        addLives=awardedLives[b]
        if addLives!=0:
            print("You have gained {} extra lives".format(addLives))
            gameLives+=addLives
        wonGame+=1
    a,b=a+1,b+1
score=gameLives+10*(hints-1)
print("Calculating your score.\nYour score is {} . Well done!".format(score))

Solution

  • This was the smallest that I ever managed to get the program with still working in the same way, in the question the code was 63 lines, I managed to reduce it to 29 lines;

    import random; gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
    def is_valid(y):
        try:y=int(y);return True
        except:print("Try again, not a number")
    def GameLevel(Range,gameLives,level,hints):
        lives,hints,targetnumber=gameLives,hints,random.randint(1,Range);print("LEVEL {}\nThinking...".format(level))
        if level>1:print("You now have {} lives remaining".format(gameLives))
        if level==int(levels[-1]):print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
        print("This number is between 1 and "+str(Range))
        while True:
            guess=input("What is your guess? ");targetnumber=str(targetnumber)
            if guess.lower()=="hint":
                if level>=3:
                    if hints!=1:targetnumber,hints=int(targetnumber),hints-1;print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
                    else:print("Sorry you have ran out of hints :(")
                else:print("Hints are not available until level 3")
            elif guess==targetnumber:print("Well done, You have guessed my number!");return lives,hints
            elif guess!=targetnumber and is_valid(guess)==True:
                print("Sorry that is not my number, you have lost a life. :(");guess,targetnumber,lives=int(guess),int(targetnumber),lives-1
                if lives<=0:exit(input("You have lost all your lives, so this means I win\nThe program will now end\n"))
                print("The target number is {}".format("higher" if (guess<targetnumber) else "lower"))
    print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)));a,b=0,0
    for level in levels:
        gameLives,hints=GameLevel((levelRange[a]),gameLives,level,hints)
        if gameLives>0 and wonGame!=int(levels[-1]):
            if awardedLives[b]>0:print("You have gained {} extra lives".format(awardedLives[b]));gameLives+=awardedLives[b]
            wonGame+=1
        a,b=a+1,b+1
    input("Calculating your score.\nYour score is {} . Well done!".format(gameLives+10*(hints-1)))