“if”语句在python3.4中无法正常运行

2024-06-02 04:54:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在建立一个猜测数字游戏,并希望使它,所以你必须解锁水平。我已经计算出了代码(或者我相信是这样),但是当它声明级别已解锁时,它不允许您选择它。(我是初学者,请配合我的编程知识差)这是我的代码:

我的问题是:

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

它打印出“Custom has been unlocked”(自定义已解锁),但实际上并不解锁位于此处的自定义范围:

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

Tags: the代码true声明游戏ifdefcustom
2条回答

给你,我通常不这么做。你知道吗

如上所述,在函数中设置isCustomUnlocked。我仔细检查了你的代码,并冒昧地改进了一下。你应该考虑减少睡眠时间。尽可能地重用代码。你知道吗

读一点关于格式化和python的知识,但总的来说,我认为它对初学者来说很不错。你知道吗

当脚本要求用户选择一个级别时,您可能需要用提示来修改逻辑。如果你回答得太快,你会收到一条错误消息,因为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()

在这里设置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。但是,为此创建一个类将产生更好的代码。你知道吗

相关问题 更多 >