-1

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))
WhatsThePoint
  • 3,395
  • 8
  • 31
  • 53
  • 4
    If this works without error, it belongs on CR or Code Golf. – TigerhawkT3 Nov 15 '16 at 08:26
  • well like i said it was about twice as long originally, and i cant find anything else so i was wondering if you guys could enlighten me – WhatsThePoint Nov 15 '16 at 08:34
  • @TigerhawkT3 what exactly are those? – WhatsThePoint Nov 15 '16 at 08:36
  • 1
    You can submit your source code to the [Code Review Stack](http://codereview.stackexchange.com/). – J. Piquard Nov 15 '16 at 08:41
  • 1
    Your program would be more pleasant to read if you _increase_ the line count a little. Don't jam everything together like that, add some whitespace! Function definitions should have a blank line above & below them, operators and equals signs should have a space either side, etc. See [PEP-0008](https://www.python.org/dev/peps/pep-0008). Also don't use "naked" `except`: it's much better to give the actual Exception names (like `ValueError`) that you want to catch. – PM 2Ring Nov 15 '16 at 08:57
  • 1
    @J.Piquard While [Code Review](http://codereview.stackexchange.com/tour) might be a good place to suggest going for this type of question, we should get out of the habit of sending question-askers over there. Please read [this](http://meta.codereview.stackexchange.com/questions/5777/a-guide-to-code-review-for-stack-overflow-users) meta post for clarification. – PM 2Ring Nov 15 '16 at 09:11
  • 1
    @PM2Ring, I have just answered in place of TigerhawkT3 to decode **CR** meaning. Regarding your suggested meta post, because the Question request **"make the code more efficient"** and **"works without error"**, Code Review seems adapted. – J. Piquard Nov 15 '16 at 10:29
  • @J.Piquard Understood. And WhatsThePoint may certainly benefit from a code review on CR. But they need to understand how to present their question so that it will be acceptable on CR: it's rare that simply duplicating an SO question on CR is desirable from the CR community's POV. – PM 2Ring Nov 15 '16 at 11:01
  • You can use the [Python ternary expression](http://stackoverflow.com/a/11529301/6945651) to if/print. (ex: `print("The target number is {}".format("higher" if (guess – J. Piquard Nov 15 '16 at 13:16
  • @J.Piquard thanks, i tried it yesterday and managed to find a few redundant lines so i have the count down to 53 – WhatsThePoint Nov 16 '16 at 09:08
  • What is your focus lines counter ? – J. Piquard Nov 16 '16 at 09:19

1 Answers1

0

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)))
WhatsThePoint
  • 3,395
  • 8
  • 31
  • 53