2014-12-13 70 views
-2

我正在構建一個猜數字遊戲,並希望使它成爲必須解鎖的級別。我已經找到了代碼(或者我相信),但是當它聲明級別已解鎖時,它不會讓您選擇它。 (我是初學者,請與我可憐的編程知識應付)這裏是我的代碼:如果我有我的問題'if'語句無法正常工作 - Python 3.4

是在這裏:

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

它打印出的是「自定義已經解鎖」,但實際上並沒有解開其中就設在這裏定製範圍:

def main(): 
    ... 
     if isCustomUnlocked == True: 
      if choice == 6: 
       cls() 
       show_loading 
+1

你需要描述更多的細節問題出在哪裏,不只是傾倒在我們的代碼。如果你沒有做到你期望的事情?你能指望什麼?會發生什麼呢? – 2014-12-13 12:04:33

+0

請參閱http://stackoverflow.com/help/mcve – tripleee 2014-12-13 12:05:28

+0

我更新了我的問題。 @JoachimSauer – orias 2014-12-13 12:09:19

回答

4

您設置isCustomUnlocked這裏:

if score <= 5: 
    isCustomUnlocked = True 

但是,由於您在函數中,因此它設置了局部變量,而不是全局變量。添加global isCustomUnlocked到您的函數的開始:

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

詳情請參閱Using global variables in a function other than the one that created them。但是,爲此創建一個類將導致更好的代碼。

+0

啊,我的程序現在工作。謝謝。 – orias 2014-12-13 12:17:20

+0

在'main'中設置'global isCustomUnlocked'會更乾淨,因爲它沒有在主要 – Aprillion 2014-12-13 12:27:41

+0

@Aprillion True中設置的局部變量,但我寧願不使用全局變量。 – matsjoyce 2014-12-13 12:35:31

2

在這裏,我通常不會這樣做。

正如上面提到的人,你在函數中設置了isCustomUnlocked。我檢查了你的代碼,並冒昧地稍微改進它。你應該考慮降低睡眠時間。儘可能重用代碼。

閱讀格式化一點點和蟒蛇,但總的來說,我認爲它對初學者來說看起來不錯。

當腳本要求用戶選擇一個級別時,您可能希望用提示修改邏輯。如果你回答太快,你會得到一個錯誤消息,因爲var是未定義的。

另外:考慮使用IDE進行開發,我推薦pyCharm。由於突出顯示,您幾秒鐘內就會發現錯誤。

#!/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() 
+0

:o謝謝!我會用這個。 – orias 2014-12-13 14:09:15

+0

小upvote非常感謝:)如果您有任何其他問題隨時與我聯繫。 – alexisdevarennes 2014-12-13 14:15:02

+0

我提高了它。我需要一段時間才能閱讀並理解它所做的一切,但是感謝您重寫它。 – orias 2014-12-13 16:10:12