我正在构建一个Guess the Number游戏,并且希望能够实现它,所以你必须解锁水平。我已经找到了代码(或者我相信),但是当它声明级别被解锁时,它不会让你选择它。 (我是初学者,请应对我糟糕的编程知识)这是我的代码:
我遇到问题的地方在这里:
def the_game(difficulty_name, range_start, range_end):
....
if score <= 5:
isCustomUnlocked = True
print ("You unlocked the Custom range!")
打印出&#34;自定义已解锁&#34;,但实际上并未解锁位于此处的自定义范围:
def main():
...
if isCustomUnlocked == True:
if choice == 6:
cls()
show_loading
答案 0 :(得分: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。但是,为此创建一个类将产生更好的代码。
答案 1 :(得分: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()