作为第一个项目,我正在命令行Python中做一个Numberama副本。 This是我尝试制作的游戏的一个很好的例子。
from os import system, name
game = []
with open("default","r") as file:
for line in file :
#print(type(line))
#line.strip('\n')
for chr in line :
if(chr!='\n'):
game.append(int(chr))
print(game)
# clear screen
def clear() :
# windows
if (name == 'nt') :
_ = system('cls')
# linux/macOS
else :
_ = system('clear')
# check if game is won (everything is 0)
def win() :
for n in game :
if (n != 0) :
return False
return True
# display current board
def display() :
clear()
for pos in range(0,len(game)) :
print(game[pos], end=' ')
if((pos+1) % 9 == 0) :
print('\n')
def add_numbers():
for n in game :
if(n) :
game.append(n)
def input_pos() :
pass
return 0
def input_dir(pos) :
pass
return 0
def check_solve() :
pass
return True
while(win() == False) :
# display board
display()
# check if there are possible pairs
solve = check_solve()
print("Type 'z' to add numbers.")
if(solve) :
print("Type 'x' to clear a pair")
# input option
opt = input('> ')
if(opt == 'z'):
add_numbers()
elif(opt == 'x' and solve == True):
pos1 = input_pos()
pos2 = input_dir(pos1)
if(game[pos1] == game[pos2] or game[pos1] + game[pos2] == 10) :
game[pos1] = 0
game[pos2] = 0
elif(opt == 'q'):
break
print('Thanks for playing Numberama!')
default
文件存储前三行,例如示例链接中的行。
一旦我在IDLE或通过终端(python3 numberama.py
)运行该程序,然后键入'z'来“添加数字”,该程序将什么也不做。我仍然可以打字,但仍然无法执行任何操作。
在命令提示符下,当我执行“ ctrl + c”以停止python时,这是输出:
Traceback (most recent call last):
File "numberama.py", line 69, in <module>
add_numbers()
File "numberama.py", line 43, in add_numbers
game.append(n)
KeyboardInterrupt
在我输入“ z”后,我的CPU使用率也从10%上升到30-50%,最终飙升到80%,直到我强制退出程序。
答案 0 :(得分:3)
这里:
def add_numbers():
for n in game :
if(n) :
game.append(n)
您正在遍历game
的末尾附加项目-这样就永远不会到达末尾。我不确定您打算在这里做什么。
答案 1 :(得分:0)
这里:
def add_numbers():
for n in game :
if(n) :
game.append(n)
将游戏项目追加到游戏中永远不会结束!(挂在我的电脑上:p)
相反,您需要这个
def add_numbers():
nos = str(input("Enter nos > "))
for n in nos:
game.append(int(n))