-2

I am building a Guess the Number game and wish to make it so you have to unlock levels. I have the code figured out (or so I believe), but when it states that the level is unlocked, it doesn't let you select it. (I am a beginner, please cope with my poor programming knowledge) Here is my code:

Where I am having my issue is here:

def the_game(difficulty_name, range_start, range_end):
    ....
            if score <= 5:
                isCustomUnlocked = True
                print ("You unlocked the Custom range!")

It prints out that "Custom has been unlocked", but does not actually unlock Custom range which is located here:

def main():
    ...
        if isCustomUnlocked == True:
            if choice == 6:
                cls()
                show_loading
Aprillion
  • 21,510
  • 5
  • 55
  • 89
  • 1
    You need to describe in much more detail where the problem is, don't just dump the code on us. Which if doesn't do what you expect? What *do* you expect? What happens instead? – Joachim Sauer Dec 13 '14 at 12:04
  • See also http://stackoverflow.com/help/mcve – tripleee Dec 13 '14 at 12:05
  • Are those two code blocks in the same function? BTW, you should probably be using `elif`s rather than a cascade of `if`s. – PM 2Ring Dec 13 '14 at 12:17
  • your update to the question was not very helpful, I removed the irrelevant code from your original question to illustrate the problem better - in order for the accepted answer to make sense – Aprillion Dec 13 '14 at 12:23

2 Answers2

3

You set isCustomUnlocked here:

if score <= 5:
    isCustomUnlocked = True

However, since you are in a function, this sets a local variable, not the global variable. Add global isCustomUnlocked to the start of your function:

def the_game(difficulty_name, range_start, range_end):
    global isCustomUnlocked
    # ...

See Using global variables in a function other than the one that created them for more details. However, making a class for this will result in nicer code.

Community
  • 1
  • 1
matsjoyce
  • 5,744
  • 6
  • 31
  • 38
1

Here you go, I usually don't do this.

As the above person mentioned, you set isCustomUnlocked in a function. I went over your code and took the liberty to improve it a little bit. You should consider lowering the sleep times. And reusing code as much as possible.

Read up on formatting a little bit and python, but overall I think it looks good for a beginner.

You might want to rework the logic with the prompt when the script asks the user to pick a level. If you answer too fast, you get an error messages because the var is undefined.

Also: Consider using an IDE for development, I recommend pyCharm. You would have spotted the error within seconds thanks the its highlighting.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import os
import sys
import time
from random import randrange, uniform
from subprocess import call

class game():
    def __init__(self):
        self.isCustomUnlocked   = False
        self.score              = 0
    #Clear Screen
    def cls(self):
        os.system('cls')

    def messages(self, messages, callCls, increaseScore):
        for sleepTime, message in messages:
            print(message)
            time.sleep(sleepTime)
        if callCls:
            self.cls()
        if increaseScore and increaseScore > 0:
            self.score += 1

    #Actual Game
    def the_game(self, difficulty_name, range_start, range_end):
        self.cls()
        print ("Difficulty: {difficulty} \n".format(difficulty=difficulty_name))
        irand = randrange(range_start, range_end)
        while True:
            number = str(input("Pick a number {range_start} - {range_end}:".format(range_start=range_start, range_end=range_end)))
            #Checks to see if 'number' is an integer or variable.
            if not number.isdigit():
                print(number, '\nis not a number, try again.')
                continue
            #Outputs if 'number' is higher than irand.
            if float(number) > float(irand):
                self.messages(messages=[{"That's too high, try again.", 1}], callCls=True, increaseScore=1)
            #Outputs if 'number' is lower than irand.
            elif float(number) < float(irand):
                self.messages(messages=[{"That's too low, try again.", 1}], callCls=True, increaseScore=1)
            #Outputs if 'number' is equal to irand.
            elif float(number) == float(irand):
                self.score += 1
                print("\nYou got it right! You won! You guessed {score} time{plural}!\n".format(score=self.score, plural='s' if self.score > 1 else ''))
                #Writes out: Number, Difficulty, and the amount of guesses.
                with open("GTN.txt", "a") as text_file:
                    text_file.write("Number: {irand} | Difficulty: {difficulty_name} | Amount of Guesses: {score}\n".format(irand=irand, difficulty_name=difficulty_name, score=self.score))
                if self.score <= 5:
                    self.isCustomUnlocked = True
                    print ("You unlocked the Custom range!")
                elif self.score > 5:
                    print ("Try to score less than {score} to unlock Custom!".format(score=self.score))
                time.sleep(4)
                self.cls()
                self.main()
                break
    """ALL DIFICULTIES FOUND HERE:"""
    #Difficulty - Easy
    def easy(self):
        self.the_game("Easy", 1, 10)
    #Difficulty - Medium
    def medium(self):
        self.the_game("Medium", 1, 100)
    #Difficulty - Hard
    def hard(self):
        self.the_game("Hard", 1, 1000)
    #Difficulty - Ultra
    def ultra(self):
        self.the_game("Ultra", 1, 100000)
    #Difficulty - Master
    def mvp(self):
        self.the_game("MVP", 1, 1000000)
    #Difficulty - Custom
    def custom(self):
        while True:
            custo_num = input ("Please input your highest range: ")
            #Number can not be used.
            if custo_num <= 1:
                self.messages(messages=[{"You can not use this number as a custom range, please try again.", 4}], callCls=True, increaseScore=False)
                continue
            #Number - 13
            if custo_num == 13:
                self.messages(messages=[{"I seriously hate you...", 1}, {"Why do you have to do this?", 3}], callCls=True, increaseScore=False)
            #Number - 21
            if custo_num == 21:
                self.messages(messages=[{"Yo, you stupid.", 1}, {"No I not.", 1, "What's 9 + 10?", 1, "21...", 4}], callCls=True, increaseScore=False)
                self.cls()
            #Number - 42
            if custo_num == 42:
                self.messages(messages=[{"Ah, the answer to life..", 3}], callCls=True, increaseScore=False)
            #Number - 69
            if custo_num == 69:
                self.messages(messages=[{"You immature, disgusting sicko...", 1}, {"I like you... Enjoy your 69..", 2}], callCls=True, increaseScore=False)
            #Number - 1989
            if custo_num == 1989:
                self.messages(messages=[{"I hate you...", 1}, {"I hate you very, very much...", 4}], callCls=True, increaseScore=False)
            #Writes out what custo_num is.
            with open("custom#.txt", "a") as text_file:
                text_file.write("Custom Number: {custo_num}".format(custo_num=custo_num))
            #Makes custo_num an integer instead of a string.
            #Detects if custo_num is an integer or string.
            if custo_num.isdigit():
                custo_num = int(custo_num)
            else:
                self.messages(messages=[{"{custo_num}, 'is not a number, please try again.".format(custo_num=custo_num), 4}], callCls=True, increaseScore=False)
                continue
            self.the_game("Custom", 1, custo_num)
    #Loading Screen
    def show_loading_screen(self):
        time.sleep(1)
        self.cls()
        call('color 84', shell=True)
        percent = 0
        while True:
            self.cls()
            print ("Loading")
            print ("  %s" % percent)
            time.sleep(0.10)
            percent += 5
            if percent == 105:
                break
        self.cls()
        call('color 8b', shell=True)
    #Exit Screen
    def show_exit_screen(self):
        time.sleep(1)
        print ("Exiting the game!")
        time.sleep(2)
    #MainMenu
    def main(self):
        print ("Please select a difficulty when prompted!")
        time.sleep(1.5)
        while True:
            self.cls()
            time.sleep(1)
            print ("[1] Easy  [2] Medium")
            time.sleep(0.25)
            print ("[3] Hard  [4] Ultra")
            time.sleep(0.25)
            print ("[5] MVP   [6] Custom")
            print ("")
            time.sleep(1)
            choice = input ("Please Choose: ")
            try:
                choice = int(choice)
            except ValueError:
                print (choice, 'is not a menu option')
                #Easy
            if choice == 1:
                self.cls()
                self.show_loading_screen()
                self.easy()
            #Medium
            if choice == 2:
                self.cls()
                self.show_loading_screen()
                self.medium()
            #Hard
            if choice == 3:
                self.cls()
                self.show_loading_screen()
                self.hard()
            #Ultra
            if choice == 4:
                self.cls()
                self.show_loading_screen()
                self.ultra()
            #Master
            if choice == 5:
                self.cls()
                self.show_loading_screen()
                self.mvp()
            #Custom Range - Must be Unlocked
            if self.isCustomUnlocked == True:
                if choice == 6:
                    self.cls()
                    self.show_loading_screen()
                    self.custom()
            #Invalid Menu option.
            else:
                self.cls()
                print ("Invalid Option: Please select from those available.")
                time.sleep(4)
                self.cls()
#Main Code
if __name__ == "__main__":
    game = game()
    call('color 8b', shell=True)
    print ("Guess the Number by: Austin Hargis")
    time.sleep(2)
    print ("Partnered with: oysterDev")
    time.sleep(3)
    game.cls()
    #Change Every Release
    isSnapshot = True
    #Prints if the release is a snapshot.
    if isSnapshot:
        snapshot = ('Snapshot: ')
        snapshotVersion = ('14w02a')
    #Prints if the release is a full version.
    elif not isSnapshot:
        snapshot = ('Version: ')
        snapshotVersion = ('1.3.0')
    call('color 84', shell=True)
    print (snapshot + snapshotVersion)
    time.sleep(3)
    game.cls()
    call('color 8b', shell=True)
    game.main()
alexisdevarennes
  • 5,437
  • 4
  • 24
  • 38
  • Small upvote very much appreciated :) If you have any other questions feel free to contact me. – alexisdevarennes Dec 13 '14 at 14:15
  • I upvoted it. It's gonna take my some time to be able to read it and understand what all of it does, but thank you for rewriting it. –  Dec 13 '14 at 16:10