我正在编写一个骰子游戏。这段代码用于输入,以确保我有正确的输入(例如 5+4*3/2-1)并且以后不会使程序崩溃。
我正在为 GUI 使用easygui。一开始的代码是这样的:
#possible_inputs = a list of operators (+-*/) and the values from the dices (1-6) as well as "OK, "Del" and "Reroll"
#raw_user_input = empty list
#br_value - the target value
#dice_value_list - the values from the dices
var = 0
while(var != possible_inputs.index("OK")):
var = eg.indexbox(raw_user_input, "Targetvalue: " + br_value_str, possible_inputs)
if(var != possible_inputs.index("OK")):
raw_user_input.append(possible_inputs[var])
if(var == possible_inputs.index("Del")):
raw_user_input[:] = []
if(var == possible_inputs.index("Reroll")):
#reroll dices
if(len(raw_user_input) == 0):
eg.msgbox("No input given", "ERROR")
return gui_input(dice_value_list, br_value)
for r in range(len(raw_user_input)):
if(r%2 == 0):
if(raw_user_input[r] not in dice_value_list):
eg.msgbox("Incorrect expression", "ERROR")
return gui_input(dice_value_list, br_value)
else:
if(raw_user_input[r] not in allowed_operators):
eg.msgbox("Incorrect expression", "ERROR")
return gui_input(dice_value_list, br_value)
它工作得很好,我的程序不会崩溃,因为输入不会出错。
但是,我应该将计算输入的函数放在 while 循环中,以便能够在消息框中实时为用户提供他们计算出的表达式。所以我把程序改成这样:
input_value_calc = 0
while(var != possible_inputs.index("OK")):
var = eg.indexbox(raw_user_input, "Target value: " + br_value_str + ", current target value " + str(input_value_calc), possible_inputs)
if(var != possible_inputs.index("OK")):
raw_user_input.append(possible_inputs[var])
if(var == possible_inputs.index("Del")):
raw_user_input[:] = []
if(var == possible_inputs.index("Reroll")):
#reroll dices
br_check, values_input, input_value_calc = user_input_value_check(raw_user_input,br_value):
def user_input_value_check(raw_user_input,br_value):
if(len(raw_user_input) == 0):
eg.msgbox("No input given", "ERROR")
gui_input(dice_value_list, br_value)
for r in range(len(raw_user_input)):
if(r%2 == 0):
if(raw_user_input[r] not in dice_value_list):
eg.msgbox("Incorrect expression", "ERROR")
gui_input(dice_value_list, br_value)
else:
if(raw_user_input[r] not in allowed_operators):
eg.msgbox("Incorrect expression", "ERROR")
gui_input(dice_value_list, br_value)
#rest of the program calculates the score, which works fine
#the function returns True/False (if the input evaluates to the correct br_value), values_input (again for other functions in the program), input_value_calc (the evaluated input value)
如果我第一次给出正确的输入,一切都很好,但我现在的问题是每次我给出错误的输入(2 个运算符或 2 个彼此相邻的值,从一个运算符等开始)它说我错了,让我给另一个输入。但是这次按钮无法正常工作(例如,我按下 del 并在我的输入中添加了“del”)
我真的很感谢有人在这方面给我帮助!谢谢!